"use client";

import * as React from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { toast } from "sonner";
import { Loader2, Trash2, Check } from "lucide-react";

const STATUSES = ["NEW", "READ", "RESPONDED", "CLOSED"] as const;
type Status = (typeof STATUSES)[number];

const STATUS_STYLES: Record<string, string> = {
  NEW: "bg-amber-500/10 text-amber-700 border-amber-500/20",
  READ: "bg-blue-500/10 text-blue-700 border-blue-500/20",
  RESPONDED: "bg-emerald-500/10 text-emerald-700 border-emerald-500/20",
  CLOSED: "bg-zinc-500/10 text-zinc-600 border-zinc-500/20",
};

export function LeadStatusManager({
  leadId,
  initialStatus,
}: {
  leadId: string;
  initialStatus: string;
}) {
  const router = useRouter();
  const [status, setStatus] = React.useState<string>(initialStatus);
  const [busy, setBusy] = React.useState<string | null>(null);
  const [deleting, setDeleting] = React.useState(false);
  const autoMarkedRef = React.useRef(false);

  // Auto-mark as READ when loaded with status NEW
  React.useEffect(() => {
    if (autoMarkedRef.current) return;
    autoMarkedRef.current = true;
    if (initialStatus === "NEW") {
      void updateStatus("READ", true);
    }
    // updateStatus is a stable closure using refs/state setters; safe to run once
  }, []);

  const updateStatus = async (next: Status, silent = false) => {
    setBusy(next);
    try {
      const res = await fetch(`/api/admin/leads/${leadId}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ status: next }),
      });
      if (!res.ok) {
        const d = await res.json().catch(() => ({}));
        throw new Error(d.error || "Failed to update status");
      }
      setStatus(next);
      if (!silent) toast.success(`Marked as ${next}`);
      router.refresh();
    } catch (err: any) {
      toast.error(err.message || "Update failed");
    } finally {
      setBusy(null);
    }
  };

  const onDelete = async () => {
    if (!confirm("Delete this lead permanently? This cannot be undone.")) return;
    setDeleting(true);
    try {
      const res = await fetch(`/api/admin/leads/${leadId}`, { method: "DELETE" });
      if (!res.ok) throw new Error("Failed to delete");
      toast.success("Lead deleted");
      router.push("/admin/leads");
      router.refresh();
    } catch (err: any) {
      toast.error(err.message || "Delete failed");
      setDeleting(false);
    }
  };

  return (
    <div className="space-y-4">
      <div className="flex flex-wrap items-center gap-2">
        <span className="text-sm font-medium mr-2">Status:</span>
        <Badge variant="outline" className={`text-xs font-bold uppercase ${STATUS_STYLES[status] || ""}`}>
          {status}
        </Badge>
      </div>

      <div className="flex flex-wrap gap-2">
        {STATUSES.map((s) => {
          const active = status === s;
          const isLoading = busy === s;
          return (
            <Button
              key={s}
              type="button"
              size="sm"
              variant={active ? "default" : "outline"}
              disabled={busy !== null || deleting}
              onClick={() => updateStatus(s)}
              className={active ? "brand-gradient text-white" : ""}
            >
              {isLoading ? (
                <Loader2 className="size-3.5 mr-1.5 animate-spin" />
              ) : active ? (
                <Check className="size-3.5 mr-1.5" />
              ) : null}
              {s}
            </Button>
          );
        })}
      </div>

      <div className="pt-2 border-t">
        <Button
          type="button"
          variant="ghost"
          size="sm"
          className="text-destructive hover:text-destructive"
          disabled={busy !== null || deleting}
          onClick={onDelete}
        >
          {deleting ? <Loader2 className="size-4 mr-1.5 animate-spin" /> : <Trash2 className="size-4 mr-1.5" />}
          Delete Lead
        </Button>
      </div>
    </div>
  );
}
