"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 MyDesign {
  id: string;
  name: string;
  category: string;
  background_css: string;
  price_cents: number;
  is_published: boolean;
  purchase_count: number;
}

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

export function MyDesignsModal({ open, onClose, onChanged }: MyDesignsModalProps) {
  const [designs, setDesigns] = useState<MyDesign[]>([]);
  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/designs");
      const json = await res.json();
      if (!res.ok) throw new Error(json.error || "Could not load your designs");
      setDesigns(json.designs || []);
      setPriceDrafts(
        Object.fromEntries((json.designs || []).map((d: MyDesign) => [d.id, (d.price_cents / 100).toString()]))
      );
    } catch (err) {
      setError(err instanceof Error ? err.message : "Could not load your designs");
    } finally {
      setLoading(false);
    }
  }

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

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

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

  async function remove(id: string) {
    setDeletingId(id);
    try {
      const res = await fetch("/api/notes/designs", {
        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 design");
      setDesigns((prev) => prev.filter((d) => d.id !== id));
      setConfirmDeleteId(null);
      onChanged();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Could not delete design");
    } finally {
      setDeletingId(null);
    }
  }

  return (
    <Modal open={open} onClose={onClose} title="My designs" description="Manage the designs you've uploaded 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>
      ) : designs.length === 0 ? (
        <p className="py-8 text-center text-sm text-muted-foreground">
          You haven&apos;t uploaded any designs yet.
        </p>
      ) : (
        <div className="max-h-[60vh] space-y-3 overflow-y-auto">
          {designs.map((design) => (
            <div key={design.id} className="rounded-xl border border-border/60 bg-background/60 p-3">
              <div className="flex items-center gap-3">
                <div className="h-12 w-12 shrink-0 rounded-lg border border-border" style={{ background: design.background_css }} />
                <div className="min-w-0 flex-1">
                  <p className="truncate text-sm font-semibold">{design.name}</p>
                  <div className="flex items-center gap-1.5 text-[11.5px] text-muted-foreground">
                    <ShoppingBag className="h-3 w-3" />
                    {design.purchase_count} {design.purchase_count === 1 ? "sale" : "sales"}
                  </div>
                </div>
                <button
                  type="button"
                  onClick={() => void togglePublished(design)}
                  disabled={savingId === design.id}
                  className={cn(
                    "shrink-0 rounded-full border px-2.5 py-1 text-[11px] font-semibold transition-colors disabled:opacity-50",
                    design.is_published
                      ? "border-emerald-500/25 bg-emerald-500/[0.08] text-emerald-500"
                      : "border-border text-muted-foreground",
                  )}
                >
                  {design.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[design.id] ?? ""}
                    onChange={(e) => setPriceDrafts((prev) => ({ ...prev, [design.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(design)}
                  disabled={savingId === design.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 === design.id ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : "Save"}
                </button>

                {confirmDeleteId === design.id ? (
                  <div className="flex items-center gap-1.5">
                    <button
                      type="button"
                      onClick={() => void remove(design.id)}
                      disabled={deletingId === design.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 === design.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(design.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>
  );
}
