"use client";

import { useState } from "react";
import { FileText, Loader2, Lock, Search } from "lucide-react";
import { Modal } from "@/components/ui/modal";
import { cn } from "@/lib/utils";
import { useNotes, type NoteWithRelations } from "@/hooks/use-notes";
import {
  CATEGORY_META,
  NOTE_TEMPLATE_CATEGORIES,
  type NoteTemplateCategory,
} from "@/lib/notes/note-templates";

interface CreateTemplateModalProps {
  open: boolean;
  onClose: () => void;
  onCreated: () => void;
}

export function CreateTemplateModal({ open, onClose, onCreated }: CreateTemplateModalProps) {
  const { notes, loading: notesLoading } = useNotes();
  const [step, setStep] = useState<"pick" | "details">("pick");
  const [search, setSearch] = useState("");
  const [selectedNote, setSelectedNote] = useState<NoteWithRelations | null>(null);
  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [category, setCategory] = useState<NoteTemplateCategory>("custom");
  const [icon, setIcon] = useState("📄");
  const [priceEuros, setPriceEuros] = useState("0");
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const filtered = notes
    .filter((note) => (note.title || "Untitled").toLowerCase().includes(search.toLowerCase()))
    .slice(0, 30);

  function reset() {
    setStep("pick");
    setSearch("");
    setSelectedNote(null);
    setName("");
    setDescription("");
    setCategory("custom");
    setIcon("📄");
    setPriceEuros("0");
    setError(null);
  }

  function pickNote(note: NoteWithRelations) {
    setSelectedNote(note);
    setName(note.title || "Untitled");
    setStep("details");
  }

  async function handleSubmit() {
    if (!selectedNote) return;
    if (!name.trim()) return setError("Give your template a name.");

    setSubmitting(true);
    setError(null);
    try {
      const res = await fetch("/api/notes/templates", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          noteId: selectedNote.id,
          name: name.trim(),
          description: description.trim(),
          category,
          icon,
          price_euros: priceEuros || "0",
        }),
      });
      const json = await res.json();
      if (!res.ok) throw new Error(json.error || "Template could not be created");

      reset();
      onCreated();
      onClose();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Template could not be created");
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <Modal
      open={open}
      onClose={() => {
        if (!submitting) {
          reset();
          onClose();
        }
      }}
      title={step === "pick" ? "Pick a note to turn into a template" : "Template details"}
      description={
        step === "pick"
          ? "A snapshot of its current content becomes the template — editing the note afterwards won't change the template."
          : undefined
      }
      className="max-w-lg"
    >
      {step === "pick" ? (
        <div className="space-y-3">
          <div className="relative">
            <Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
            <input
              autoFocus
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder="Search your notes…"
              className="w-full rounded-lg border border-border bg-background py-2 pl-8 pr-2 text-sm outline-none focus:border-ring"
            />
          </div>
          <div className="max-h-72 space-y-0.5 overflow-y-auto">
            {notesLoading ? (
              <div className="flex justify-center py-4">
                <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
              </div>
            ) : filtered.length === 0 ? (
              <p className="px-2 py-4 text-center text-[12px] text-muted-foreground">No notes found</p>
            ) : (
              filtered.map((note) => {
                const fromPaidTemplate = (note.source_template_price_cents || 0) > 0;
                return (
                  <button
                    key={note.id}
                    type="button"
                    onClick={() => !fromPaidTemplate && pickNote(note)}
                    disabled={fromPaidTemplate}
                    title={fromPaidTemplate ? "This note came from a paid template and can't be republished as one" : undefined}
                    className="flex w-full items-center gap-2 rounded-lg px-2 py-2 text-left text-sm transition-colors hover:bg-accent disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:bg-transparent"
                  >
                    <FileText className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
                    <span className="truncate">{note.title || "Untitled"}</span>
                    {fromPaidTemplate && <Lock className="ml-auto h-3 w-3 shrink-0 text-muted-foreground" />}
                  </button>
                );
              })
            )}
          </div>
        </div>
      ) : (
        <div className="space-y-4">
          <button type="button" onClick={() => setStep("pick")} className="text-xs font-medium text-muted-foreground hover:text-foreground">
            ← Pick a different note
          </button>

          <div className="space-y-1.5">
            <label className="text-xs font-medium text-muted-foreground">Name</label>
            <input
              value={name}
              onChange={(e) => setName(e.target.value)}
              className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm outline-none focus:border-ring"
            />
          </div>

          <div className="space-y-1.5">
            <label className="text-xs font-medium text-muted-foreground">Description</label>
            <input
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="What is this template for?"
              className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm outline-none focus:border-ring"
            />
          </div>

          <div className="grid grid-cols-[1fr_auto] gap-3">
            <div className="space-y-1.5">
              <label className="text-xs font-medium text-muted-foreground">Category</label>
              <select
                value={category}
                onChange={(e) => setCategory(e.target.value as NoteTemplateCategory)}
                className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm outline-none focus:border-ring"
              >
                {NOTE_TEMPLATE_CATEGORIES.map((cat) => (
                  <option key={cat} value={cat}>
                    {CATEGORY_META[cat].label}
                  </option>
                ))}
              </select>
            </div>
            <div className="space-y-1.5">
              <label className="text-xs font-medium text-muted-foreground">Icon</label>
              <input
                value={icon}
                onChange={(e) => setIcon(e.target.value)}
                maxLength={4}
                className="w-16 rounded-lg border border-border bg-background px-3 py-2 text-center text-sm outline-none focus:border-ring"
              />
            </div>
          </div>

          <div className="space-y-1.5">
            <label className="text-xs font-medium text-muted-foreground">Price (€, 0 = free)</label>
            <input
              type="number"
              min={0}
              step={0.5}
              value={priceEuros}
              onChange={(e) => setPriceEuros(e.target.value)}
              className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm outline-none focus:border-ring"
            />
          </div>

          {error && <p className="text-xs text-destructive">{error}</p>}

          <button
            type="button"
            onClick={() => void handleSubmit()}
            disabled={submitting}
            className={cn(
              "flex w-full items-center justify-center gap-2 rounded-lg bg-primary px-4 py-2.5 text-sm font-semibold text-primary-foreground transition-colors hover:bg-primary/90 disabled:opacity-60",
            )}
          >
            {submitting && <Loader2 className="h-4 w-4 animate-spin" />}
            {submitting ? "Publishing…" : "Publish to marketplace"}
          </button>
        </div>
      )}
    </Modal>
  );
}
