"use client";

import { useEffect, useState } from "react";
import { Loader2, ShoppingBag, Trash2 } from "lucide-react";
import { Modal } from "@/components/ui/modal";
import { cn } from "@/lib/utils";

interface MyTemplate {
  id: string;
  name: string;
  description: string;
  icon: string;
  price_cents: number;
  is_published: boolean;
  purchase_count: number;
}

interface MyTemplatesModalProps {
  open: boolean;
  onClose: () => void;
  onChanged: () => void;
}

export function MyTemplatesModal({ open, onClose, onChanged }: MyTemplatesModalProps) {
  const [templates, setTemplates] = useState<MyTemplate[]>([]);
  const [loading, setLoading] = useState(true);
  const [priceDrafts, setPriceDrafts] = useState<Record<string, string>>({});
  const [savingId, setSavingId] = useState<string | null>(null);
  const [deletingId, setDeletingId] = useState<string | null>(null);
  const [confirmDeleteId, setConfirmDeleteId] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  async function load() {
    setLoading(true);
    setError(null);
    try {
      const res = await fetch("/api/notes/templates");
      const json = await res.json();
      if (!res.ok) throw new Error(json.error || "Could not load your templates");
      setTemplates(json.templates || []);
      setPriceDrafts(
        Object.fromEntries((json.templates || []).map((t: MyTemplate) => [t.id, (t.price_cents / 100).toString()]))
      );
    } catch (err) {
      setError(err instanceof Error ? err.message : "Could not load your templates");
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    if (open) void load();
  }, [open]);

  async function savePrice(template: MyTemplate) {
    setSavingId(template.id);
    try {
      const res = await fetch("/api/notes/templates", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id: template.id, price_euros: priceDrafts[template.id] }),
      });
      const json = await res.json();
      if (!res.ok) throw new Error(json.error || "Could not update price");
      setTemplates((prev) => prev.map((t) => (t.id === template.id ? { ...t, ...json.template } : t)));
      onChanged();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Could not update price");
    } finally {
      setSavingId(null);
    }
  }

  async function togglePublished(template: MyTemplate) {
    setSavingId(template.id);
    try {
      const res = await fetch("/api/notes/templates", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id: template.id, is_published: !template.is_published }),
      });
      const json = await res.json();
      if (!res.ok) throw new Error(json.error || "Could not update template");
      setTemplates((prev) => prev.map((t) => (t.id === template.id ? { ...t, ...json.template } : t)));
      onChanged();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Could not update template");
    } finally {
      setSavingId(null);
    }
  }

  async function remove(id: string) {
    setDeletingId(id);
    try {
      const res = await fetch("/api/notes/templates", {
        method: "DELETE",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id }),
      });
      const json = await res.json();
      if (!res.ok) throw new Error(json.error || "Could not delete template");
      setTemplates((prev) => prev.filter((t) => t.id !== id));
      setConfirmDeleteId(null);
      onChanged();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Could not delete template");
    } finally {
      setDeletingId(null);
    }
  }

  return (
    <Modal open={open} onClose={onClose} title="My templates" description="Manage the templates you've published to the marketplace." className="max-w-lg">
      {error && <p className="mb-3 text-xs text-destructive">{error}</p>}

      {loading ? (
        <div className="flex justify-center py-10">
          <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
        </div>
      ) : templates.length === 0 ? (
        <p className="py-8 text-center text-sm text-muted-foreground">
          You haven&apos;t published any templates yet.
        </p>
      ) : (
        <div className="max-h-[60vh] space-y-3 overflow-y-auto">
          {templates.map((template) => (
            <div key={template.id} className="rounded-xl border border-border/60 bg-background/60 p-3">
              <div className="flex items-center gap-3">
                <div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-lg border border-border bg-muted/40 text-xl">
                  {template.icon}
                </div>
                <div className="min-w-0 flex-1">
                  <p className="truncate text-sm font-semibold">{template.name}</p>
                  <div className="flex items-center gap-1.5 text-[11.5px] text-muted-foreground">
                    <ShoppingBag className="h-3 w-3" />
                    {template.purchase_count} {template.purchase_count === 1 ? "sale" : "sales"}
                  </div>
                </div>
                <button
                  type="button"
                  onClick={() => void togglePublished(template)}
                  disabled={savingId === template.id}
                  className={cn(
                    "shrink-0 rounded-full border px-2.5 py-1 text-[11px] font-semibold transition-colors disabled:opacity-50",
                    template.is_published
                      ? "border-emerald-500/25 bg-emerald-500/[0.08] text-emerald-500"
                      : "border-border text-muted-foreground",
                  )}
                >
                  {template.is_published ? "Published" : "Unpublished"}
                </button>
              </div>

              <div className="mt-3 flex items-center gap-2">
                <div className="relative flex-1">
                  <span className="pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 text-xs text-muted-foreground">
                    €
                  </span>
                  <input
                    type="number"
                    min={0}
                    step={0.5}
                    value={priceDrafts[template.id] ?? ""}
                    onChange={(e) => setPriceDrafts((prev) => ({ ...prev, [template.id]: e.target.value }))}
                    className="w-full rounded-lg border border-border bg-background py-1.5 pl-6 pr-2 text-sm outline-none focus:border-ring"
                  />
                </div>
                <button
                  type="button"
                  onClick={() => void savePrice(template)}
                  disabled={savingId === template.id}
                  className="rounded-lg border border-border px-3 py-1.5 text-[12.5px] font-semibold transition-colors hover:bg-accent disabled:opacity-50"
                >
                  {savingId === template.id ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : "Save"}
                </button>

                {confirmDeleteId === template.id ? (
                  <div className="flex items-center gap-1.5">
                    <button
                      type="button"
                      onClick={() => void remove(template.id)}
                      disabled={deletingId === template.id}
                      className="rounded-lg bg-destructive px-2.5 py-1.5 text-[12.5px] font-semibold text-destructive-foreground hover:bg-destructive/90 disabled:opacity-50"
                    >
                      {deletingId === template.id ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : "Confirm"}
                    </button>
                    <button
                      type="button"
                      onClick={() => setConfirmDeleteId(null)}
                      className="rounded-lg border border-border px-2.5 py-1.5 text-[12.5px] font-medium text-muted-foreground hover:bg-accent"
                    >
                      Cancel
                    </button>
                  </div>
                ) : (
                  <button
                    type="button"
                    onClick={() => setConfirmDeleteId(template.id)}
                    title="Delete"
                    className="rounded-lg border border-border p-1.5 text-muted-foreground transition-colors hover:border-destructive/40 hover:text-destructive"
                  >
                    <Trash2 className="h-3.5 w-3.5" />
                  </button>
                )}
              </div>
            </div>
          ))}
        </div>
      )}
    </Modal>
  );
}
