import { useRef, useState } from "react";
import { toast } from "sonner";
import { BookOpen, Upload } from "lucide-react";
import type { Extension } from "@codemirror/state";
import * as api from "@/api/client";
import EditorPane from "./EditorPane";
import { EXAMPLES } from "./examples";
import {
  Popover,
  PopoverTrigger,
  PopoverContent,
  PopoverHeader,
  PopoverTitle,
} from "@/components/ui/popover";

interface SourcePaneProps {
  ufSource: string;
  setSource: (s: string) => void;
  extensions: Extension[];
}

export default function SourcePane({ ufSource, setSource, extensions }: SourcePaneProps) {
  const [examplesOpen, setExamplesOpen] = useState(false);
  const fileRef = useRef<HTMLInputElement>(null);
  const [uploading, setUploading] = useState(false);

  const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setUploading(true);
    try {
      const data = await api.uploadImage(file);
      toast.success(`Uploaded ${data.filename}`);
      setSource(`image "${data.path}" braille 30\n  align center`);
    } catch (err) {
      toast.error(`Upload failed: ${err}`);
    } finally {
      setUploading(false);
      if (fileRef.current) fileRef.current.value = "";
    }
  };

  return (
    <div className="flex flex-col h-full">
      <div className="flex items-center px-4 py-2 border-b-2 border-border shrink-0 gap-2">
        <span className="font-medium text-foreground flex-1">Source</span>

        <Popover open={examplesOpen} onOpenChange={setExamplesOpen}>
          <PopoverTrigger
            render={
              <button className="text-[10px] text-muted-foreground hover:text-foreground transition-colors uppercase tracking-wider flex items-center gap-1 cursor-pointer">
                <BookOpen className="h-3 w-3" />
                Examples
              </button>
            }
          />
          <PopoverContent side="bottom" align="end" sideOffset={8}>
            <PopoverHeader>
              <PopoverTitle>Insert Example</PopoverTitle>
            </PopoverHeader>
            <div className="flex flex-col gap-0.5 max-h-72 overflow-y-auto -mx-1">
              {EXAMPLES.map((ex) => (
                <button
                  key={ex.name}
                  onClick={() => { setSource(ex.source); setExamplesOpen(false); }}
                  className="flex flex-col items-start px-2 py-1.5 text-left hover:bg-accent transition-colors cursor-pointer"
                >
                  <span className="text-sm font-medium">{ex.name}</span>
                  <span className="text-xs text-muted-foreground leading-tight">{ex.description}</span>
                </button>
              ))}
            </div>
          </PopoverContent>
        </Popover>

        <input ref={fileRef} type="file" accept="image/*" className="hidden" onChange={handleUpload} />
        <button
          onClick={() => fileRef.current?.click()}
          disabled={uploading}
          className="text-[10px] text-muted-foreground hover:text-foreground transition-colors uppercase tracking-wider flex items-center gap-1 disabled:opacity-50 cursor-pointer"
        >
          <Upload className="h-3 w-3" />
          {uploading ? "Uploading\u2026" : "Image"}
        </button>
      </div>
      <div className="flex-1 overflow-auto min-h-0">
        <EditorPane value={ufSource} onChange={setSource} extensions={extensions} />
      </div>
    </div>
  );
}
