"use client";

import { useMemo, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { Search, Trash2, ArrowLeft, RefreshCw, Download } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardBody } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { formatDateTime as fmtDate, initials } from "@/lib/utils";

type Contact = any;

export function InvalidContactsClient({
  initialContacts,
}: {
  initialContacts: Contact[];
}) {
  const router = useRouter();
  const [query, setQuery] = useState("");
  const [deletingAll, setDeletingAll] = useState(false);

  async function deleteAll() {
    if (!confirm("Are you sure you want to delete all blocked and invalid contacts? This cannot be undone.")) return;
    setDeletingAll(true);
    const res = await fetch("/api/contacts/invalid/delete-all", { method: "DELETE" });
    setDeletingAll(false);
    if (!res.ok) return toast.error("Failed to delete contacts.");
    toast.success("All blocked and invalid contacts deleted.");
    router.refresh();
  }

  const list = useMemo(() => {
    let items = initialContacts;
    if (query) {
      const q = query.toLowerCase();
      items = items.filter(
        (c) =>
          c.name.toLowerCase().includes(q) ||
          c.phone.includes(q) ||
          (c.email ?? "").toLowerCase().includes(q)
      );
    }
    return items;
  }, [initialContacts, query]);

  return (
    <div className="space-y-4">
      <div className="flex flex-wrap items-center gap-2">
        <div className="relative min-w-64 flex-1">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <Input
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder="Search blocked or invalid..."
            className="pl-9"
          />
        </div>
        <Button variant="destructive" onClick={deleteAll} disabled={deletingAll || initialContacts.length === 0}>
          {deletingAll ? <RefreshCw className="h-4 w-4 mr-2 animate-spin" /> : <Trash2 className="h-4 w-4 mr-2" />} Delete All
        </Button>
        <Button variant="outline" onClick={() => router.push('/api/contacts/invalid/export')}>
          <Download className="h-4 w-4 mr-2" /> Export CSV
        </Button>
        <Button variant="outline" onClick={() => router.push('/contacts')}>
          <ArrowLeft className="h-4 w-4 mr-2" /> Back to Contacts
        </Button>
      </div>

      <Card>
        <CardBody className="px-0">
          {list.length === 0 ? (
            <p className="px-5 py-10 text-center text-sm text-muted-foreground">
              No contacts yet. Add one manually or import a CSV.
            </p>
          ) : (
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-border text-left text-xs uppercase tracking-wide text-muted-foreground">
                  <th className="px-5 py-3 font-medium">Name</th>
                  <th className="px-5 py-3 font-medium">Phone</th>
                  <th className="px-5 py-3 font-medium">Reason</th>
                  <th className="px-5 py-3 font-medium">Status</th>
                  <th className="px-5 py-3 font-medium">Updated</th>
                  <th className="px-5 py-3 text-right">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-border">
                {list.map((c) => (
                  <tr key={c.id} className="group hover:bg-muted">
                    <td className="px-5 py-3">
                      <Link href={`/contacts/${c.id}`} className="flex items-center gap-2 font-medium text-foreground hover:text-indigo-600">
                        <span className="flex h-7 w-7 items-center justify-center rounded-full bg-indigo-100 text-xs font-semibold text-indigo-700">
                          {initials(c.name)}
                        </span>
                        {c.name}
                      </Link>
                    </td>
                    <td className="px-5 py-3 text-muted-foreground">{c.phone}</td>
                    <td className="px-5 py-3 text-muted-foreground truncate max-w-[250px]" title={c.broadcastRecipients?.[0]?.error || "Invalid format or opted out"}>
                      {c.broadcastRecipients?.[0]?.error || "Invalid format or opted out"}
                    </td>
                    <td className="px-5 py-3">
                      <Badge tone={c.status === "INVALID" ? "red" : "gray"}>
                        {c.status}
                      </Badge>
                    </td>
                    <td className="px-5 py-3 text-muted-foreground">{fmtDate(c.updatedAt)}</td>
                    <td className="px-5 py-3 text-right">
                      <div className="flex justify-end gap-1">
                        <RestoreButton id={c.id} name={c.name} />
                        <DeleteButton id={c.id} name={c.name} />
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </CardBody>
      </Card>

    </div>
  );
}

function RestoreButton({ id, name }: { id: string; name: string }) {
  const [busy, setBusy] = useState(false);
  async function restore() {
    if (!confirm(`Restore ${name} to Active?`)) return;
    setBusy(true);
    const res = await fetch(`/api/contacts/${id}`, { 
      method: "PATCH", 
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ status: "ACTIVE" })
    });
    setBusy(false);
    if (!res.ok) return toast.error("Failed to restore.");
    toast.success("Contact restored to active.");
    routerRefresh();
  }
  return (
    <Button variant="ghost" size="icon" className="text-muted-foreground hover:text-green-600" onClick={restore} disabled={busy} title="Restore Contact">
      <RefreshCw className="h-4 w-4" />
    </Button>
  );
}

function DeleteButton({ id, name }: { id: string; name: string }) {
  const [busy, setBusy] = useState(false);
  async function remove() {
    if (!confirm(`Delete ${name}? This cannot be undone.`)) return;
    setBusy(true);
    const res = await fetch(`/api/contacts/${id}`, { method: "DELETE" });
    setBusy(false);
    if (!res.ok) return toast.error("Failed to delete.");
    toast.success("Contact deleted.");
    routerRefresh();
  }
  return (
    <Button variant="ghost" size="icon" className="text-muted-foreground hover:text-red-600" onClick={remove} disabled={busy}>
      <Trash2 className="h-4 w-4" />
    </Button>
  );
}

function routerRefresh() {
  window.location.reload();
}
