import React, { useState, useRef } from 'react';
import { BookOpen, Sparkles, Upload, FileText, Loader2 } from 'lucide-react';

interface LeftRailProps {
  onGenerate: (subject: string, notes: string) => void;
  isGenerating: boolean;
  recentPacks: { id: string; subject: string }[];
  onSelectPack: (id: string) => void;
  activePackId?: string;
}

export function LeftRail({ onGenerate, isGenerating, recentPacks, onSelectPack, activePackId }: LeftRailProps) {
  const [subject, setSubject] = useState('');
  const [notes, setNotes] = useState('');
  const [uploadedFileName, setUploadedFileName] = useState('');
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = (event) => {
      const content = event.target?.result;
      if (typeof content === 'string') {
        setNotes(content);
        setUploadedFileName(file.name);
        if (!subject) {
          setSubject(file.name.replace(/\.[^/.]+$/, ''));
        }
      }
    };
    reader.readAsText(file);
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (subject.trim() && notes.trim() && !isGenerating) {
      onGenerate(subject, notes);
    }
  };

  return (
    <aside
      id="studyflow-left-rail"
      className="studyflow-left-rail flex h-full w-80 flex-shrink-0 flex-col border-r border-white/5 bg-[#0a0f1c]"
    >
      <div className="studyflow-left-rail-header flex-shrink-0 p-6">
        <div id="studyflow-brand" className="mb-8 flex items-center gap-2">
          <div className="w-8 h-8 rounded bg-amber-500/10 flex items-center justify-center text-amber-500">
            <BookOpen size={18} />
          </div>
          <h1 className="text-xl font-medium text-zinc-100 tracking-tight">StudyFlow</h1>
        </div>

        <form id="studyflow-generate-form" onSubmit={handleSubmit} className="space-y-5">
          <div id="studyflow-subject-field" className="studyflow-form-field">
            <label htmlFor="studyflow-subject-input" className="mb-2 block text-xs font-medium uppercase tracking-wider text-zinc-400">
              Subject
            </label>
            <input
              id="studyflow-subject-input"
              type="text"
              value={subject}
              onChange={(e) => setSubject(e.target.value)}
              placeholder="e.g. Cellular Biology"
              className="w-full bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-zinc-200 placeholder:text-zinc-600 focus:outline-none focus:border-amber-500/50 focus:ring-1 focus:ring-amber-500/50 transition-all"
              required
            />
          </div>

          <div id="studyflow-notes-upload-field" className="studyflow-form-field">
            <div className="mb-3 flex items-center justify-between">
              <label htmlFor="studyflow-notes-file-input" className="block text-xs font-medium uppercase tracking-wider text-zinc-400">
                Source File
              </label>
              <button
                id="studyflow-notes-upload-trigger"
                type="button"
                onClick={() => fileInputRef.current?.click()}
                className="text-xs text-teal-500 hover:text-teal-400 flex items-center gap-1 transition-colors"
              >
                <Upload size={12} />
                Upload .txt
              </button>
              <input
                id="studyflow-notes-file-input"
                type="file"
                ref={fileInputRef}
                onChange={handleFileUpload}
                accept=".txt"
                className="hidden"
              />
            </div>

            <div
              id="studyflow-upload-status"
              className="rounded-xl border border-dashed border-white/10 bg-white/[0.03] px-4 py-4 text-sm text-zinc-300"
            >
              {uploadedFileName ? (
                <div className="flex items-start gap-3">
                  <div className="mt-0.5 rounded-md bg-amber-500/10 p-2 text-amber-400">
                    <FileText size={14} />
                  </div>
                  <div className="min-w-0">
                    <p className="font-medium text-zinc-100">Loaded file</p>
                    <p className="truncate text-zinc-400">{uploadedFileName}</p>
                    <p className="mt-1 text-xs text-zinc-500">{notes.length.toLocaleString()} characters ready for generation</p>
                  </div>
                </div>
              ) : (
                <div className="flex items-start gap-3">
                  <div className="mt-0.5 rounded-md bg-white/5 p-2 text-zinc-500">
                    <Upload size={14} />
                  </div>
                  <div>
                    <p className="font-medium text-zinc-200">Upload one text file to continue</p>
                    <p className="mt-1 text-xs text-zinc-500">The pack is generated only from the uploaded .txt file.</p>
                  </div>
                </div>
              )}
            </div>
          </div>

          <button
            id="studyflow-generate-button"
            type="submit"
            disabled={isGenerating || !subject.trim() || !notes.trim()}
            className="w-full bg-amber-600 hover:bg-amber-500 text-white rounded-lg px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {isGenerating ? (
              <>
                <Loader2 size={16} className="animate-spin" />
                Generating Pack...
              </>
            ) : (
              <>
                <Sparkles size={16} />
                Generate Study Pack
              </>
            )}
          </button>
        </form>
      </div>

      {recentPacks.length > 0 && (
        <div
          id="studyflow-recent-packs"
          className="studyflow-recent-packs flex-1 overflow-y-auto border-t border-white/5 p-6 pt-2"
        >
          <h3 className="mb-3 text-xs font-medium uppercase tracking-wider text-zinc-500">Recent Packs</h3>
          <div className="space-y-1">
            {recentPacks.map((pack) => (
              <button
                id={`studyflow-pack-${pack.id}`}
                key={pack.id}
                onClick={() => onSelectPack(pack.id)}
                className={`w-full text-left px-3 py-2 rounded-md text-sm flex items-center gap-2 transition-colors ${
                  activePackId === pack.id
                    ? 'bg-white/10 text-zinc-100'
                    : 'text-zinc-400 hover:bg-white/5 hover:text-zinc-200'
                }`}
              >
                <FileText size={14} className={activePackId === pack.id ? 'text-amber-500' : 'text-zinc-500'} />
                <span className="truncate">{pack.subject}</span>
              </button>
            ))}
          </div>
        </div>
      )}
    </aside>
  );
}
