import { useRef, useState } from "react";
import { BookOpen, ImagePlus } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Popover,
  PopoverTrigger,
  PopoverContent,
  PopoverHeader,
  PopoverTitle,
} from "@/components/ui/popover";
import { useEditorStore } from "@/stores/editorStore";
import { useBacklinks } from "@/hooks/useBacklinks";
import BacklinkIndicator from "@/components/editor/BacklinkIndicator";
import { EXAMPLES } from "@/components/editor/examples";

interface Props {
  pageName: string;
  onNameChange?: (name: string) => void;
  onSaveDraft: () => void;
  onPublish: () => void;
  onInsertExample: (source: string) => void;
  saving: boolean;
  isDirty: boolean;
}

export default function ToolBar({
  pageName,
  onNameChange,
  onSaveDraft,
  onPublish,
  onInsertExample,
  saving,
  isDirty,
}: Props) {
  const currentPage = useEditorStore((s) => s.currentPage);
  const backlinks = useBacklinks(currentPage?.name);
  const [examplesOpen, setExamplesOpen] = useState(false);

  return (
    <div className="flex items-center gap-3 px-4 py-2 border-b bg-card shrink-0">
      {onNameChange ? (
        <Input
          value={pageName}
          onChange={(e) => onNameChange(e.target.value)}
          placeholder="page-name"
          className="font-mono w-48 h-8 text-sm"
        />
      ) : (
        <span className="font-mono font-semibold text-sm">{pageName}</span>
      )}

      <Popover open={examplesOpen} onOpenChange={setExamplesOpen}>
        <PopoverTrigger
          render={
            <button
              className="inline-flex items-center justify-center gap-1.5 rounded-md text-xs font-medium h-8 px-3 border border-input bg-background hover:bg-accent hover:text-accent-foreground transition-colors"
              title="Insert example template"
            >
              <BookOpen className="h-3.5 w-3.5" />
              <span>Examples</span>
            </button>
          }
        />
        <PopoverContent side="bottom" align="start" 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={() => {
                  onInsertExample(ex.source);
                  setExamplesOpen(false);
                }}
                className="flex flex-col items-start rounded-md px-2 py-1.5 text-left hover:bg-accent transition-colors"
              >
                <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>

      <UploadImageButton onUploaded={(path) => onInsertExample(
        `image "${path}" braille 30\n  align center`
      )} />

      <div className="flex-1" />

      <BacklinkIndicator backlinks={backlinks} />

      {isDirty && (
        <span className="text-xs text-muted-foreground">Unsaved</span>
      )}

      <Button
        variant="outline"
        size="sm"
        onClick={onSaveDraft}
        disabled={saving}
      >
        Save Draft
      </Button>
      <Button size="sm" onClick={onPublish} disabled={saving}>
        Publish
      </Button>
    </div>
  );
}


function UploadImageButton({ onUploaded }: { onUploaded: (path: string) => void }) {
  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 form = new FormData();
      form.append("file", file);
      const res = await fetch("/api/upload-image", { method: "POST", body: form });
      if (!res.ok) throw new Error(await res.text());
      const data = await res.json();
      toast.success(`Uploaded ${data.filename}`);
      onUploaded(data.path);
    } catch (err) {
      toast.error(`Upload failed: ${err}`);
    } finally {
      setUploading(false);
      if (fileRef.current) fileRef.current.value = "";
    }
  };

  return (
    <>
      <input
        ref={fileRef}
        type="file"
        accept="image/*"
        className="hidden"
        onChange={handleUpload}
      />
      <button
        onClick={() => fileRef.current?.click()}
        disabled={uploading}
        className="inline-flex items-center justify-center gap-1.5 rounded-md text-xs font-medium h-8 px-3 border border-input bg-background hover:bg-accent hover:text-accent-foreground transition-colors disabled:opacity-50"
        title="Upload image for embedding"
      >
        <ImagePlus className="h-3.5 w-3.5" />
        <span>{uploading ? "Uploading…" : "Image"}</span>
      </button>
    </>
  );
}
