"use client";

import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { UserPlus, RefreshCw } from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
import { Table, TableHead, TableBody, TableRow, Th, Td, EmptyState } from "@/components/ui/Table";
import { Badge } from "@/components/ui/Badge";
import { Button } from "@/components/ui/Button";
import { Input } from "@/components/ui/Input";
import { Modal } from "@/components/ui/Modal";
import { formatDate } from "@/lib/utils";
import api from "@/lib/api";
import { toast } from "sonner";
import type { Lead } from "@/types";

const statusVariant: Record<string, "success" | "warning" | "danger" | "muted" | "default"> = {
  NEW: "muted", CONTACTED: "default" as any, INTERESTED: "warning", CONVERTED: "success", LOST: "danger",
};

const statusOptions = ["NEW", "CONTACTED", "INTERESTED", "CONVERTED", "LOST"];

export default function LeadsPage() {
  const qc = useQueryClient();
  const [search, setSearch] = useState("");
  const [selected, setSelected] = useState<Lead | null>(null);
  const [showAdd, setShowAdd] = useState(false);
  const [form, setForm] = useState({ firstName: "", lastName: "", phone: "", email: "", address: "", notes: "", source: "" });
  const [statusUpdate, setStatusUpdate] = useState("");

  const { data = [], isLoading, refetch } = useQuery<Lead[]>({
    queryKey: ["leads", search],
    queryFn: async () => {
      const params = new URLSearchParams({ limit: "100" });
      if (search) params.set("search", search);
      const res = await api.get<Lead[] | { data: Lead[] }>(`/api/v1/leads?${params}`);
      const d = res.data;
      return Array.isArray(d) ? d : d.data ?? [];
    },
  });

  const addLead = useMutation({
    mutationFn: async () => {
      await api.post("/api/v1/leads", {
        firstName: form.firstName, lastName: form.lastName,
        phone: form.phone, email: form.email || undefined,
        address: form.address || undefined, notes: form.notes || undefined,
        source: form.source || undefined,
      });
    },
    onSuccess: () => {
      toast.success("Lead added!");
      setShowAdd(false);
      setForm({ firstName: "", lastName: "", phone: "", email: "", address: "", notes: "", source: "" });
      qc.invalidateQueries({ queryKey: ["leads"] });
    },
    onError: (e: any) => toast.error(e.response?.data?.message ?? "Failed to add lead"),
  });

  const updateStatus = useMutation({
    mutationFn: async ({ id, status }: { id: string; status: string }) => {
      await api.patch(`/api/v1/leads/${id}`, { status });
    },
    onSuccess: () => {
      toast.success("Status updated!");
      qc.invalidateQueries({ queryKey: ["leads"] });
      if (selected) setSelected(prev => prev ? { ...prev, status: statusUpdate as Lead["status"] } : prev);
    },
    onError: (e: any) => toast.error(e.response?.data?.message ?? "Failed to update"),
  });

  const deleteLead = useMutation({
    mutationFn: async (id: string) => { await api.delete(`/api/v1/leads/${id}`); },
    onSuccess: () => {
      toast.success("Lead deleted");
      setSelected(null);
      qc.invalidateQueries({ queryKey: ["leads"] });
    },
    onError: (e: any) => toast.error(e.response?.data?.message ?? "Failed to delete"),
  });

  const counts = statusOptions.reduce((acc, s) => ({ ...acc, [s]: data.filter(l => l.status === s).length }), {} as Record<string, number>);

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Leads</h1>
          <p className="text-sm text-gray-500 mt-1">Prospective customers pipeline</p>
        </div>
        <div className="flex gap-2">
          <Button onClick={() => refetch()} variant="outline" size="sm"><RefreshCw size={14} className="mr-1" />Refresh</Button>
          <Button onClick={() => setShowAdd(true)} size="sm"><UserPlus size={14} className="mr-1" />Add Lead</Button>
        </div>
      </div>

      {/* Pipeline summary */}
      <div className="flex gap-3 flex-wrap">
        {statusOptions.map(status => (
          <div key={status} className="bg-white border rounded-xl px-4 py-3 text-center min-w-[90px] shadow-sm">
            <p className="text-2xl font-bold text-gray-800">{counts[status] ?? 0}</p>
            <Badge variant={statusVariant[status] ?? "muted"} className="mt-1">{status}</Badge>
          </div>
        ))}
        <div className="bg-blue-50 border border-blue-200 rounded-xl px-4 py-3 text-center min-w-[90px]">
          <p className="text-2xl font-bold text-blue-700">{data.length}</p>
          <p className="text-xs text-blue-600 font-medium mt-1">TOTAL</p>
        </div>
      </div>

      <Card>
        <CardHeader>
          <div className="flex items-center justify-between gap-4">
            <CardTitle>All Leads ({data.length})</CardTitle>
            <input className="border rounded-lg px-3 py-2 text-sm max-w-xs w-full focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="Search by name or phone..."
              value={search} onChange={e => setSearch(e.target.value)} />
          </div>
        </CardHeader>
        <CardContent className="p-0">
          <Table>
            <TableHead>
              <TableRow><Th>Name</Th><Th>Phone</Th><Th>Email</Th><Th>Address</Th><Th>Status</Th><Th>Source</Th><Th>Added</Th></TableRow>
            </TableHead>
            <TableBody>
              {isLoading ? (
                Array.from({ length: 6 }).map((_, i) => (
                  <TableRow key={i}><Td colSpan={7}><div className="h-4 bg-gray-100 rounded animate-pulse" /></Td></TableRow>
                ))
              ) : data.length === 0 ? (
                <EmptyState colSpan={7} message="No leads yet" icon={<UserPlus size={24} />} />
              ) : data.map(lead => (
                <TableRow key={lead.id} onClick={() => { setSelected(lead); setStatusUpdate(lead.status); }}
                  className="cursor-pointer hover:bg-blue-50 transition-colors">
                  <Td className="font-medium">{lead.firstName} {lead.lastName}</Td>
                  <Td>{lead.phone}</Td>
                  <Td className="text-gray-500">{lead.email ?? "—"}</Td>
                  <Td className="text-gray-500 max-w-[150px] truncate">{lead.address ?? "—"}</Td>
                  <Td><Badge variant={statusVariant[lead.status] ?? "muted"}>{lead.status}</Badge></Td>
                  <Td className="text-gray-400 text-sm">{lead.source ?? "—"}</Td>
                  <Td className="text-gray-400 text-xs">{formatDate(lead.createdAt)}</Td>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      {/* Lead Detail Modal */}
      <Modal isOpen={!!selected} onClose={() => setSelected(null)} title={`${selected?.firstName ?? ""} ${selected?.lastName ?? ""}`}>
        {selected && (
          <div className="space-y-4">
            <div className="bg-gray-50 rounded-lg p-4 space-y-2 text-sm">
              <div className="flex justify-between"><span className="text-gray-500">Phone</span><span className="font-medium">{selected.phone}</span></div>
              {selected.email && <div className="flex justify-between"><span className="text-gray-500">Email</span><span>{selected.email}</span></div>}
              {selected.address && <div className="flex justify-between"><span className="text-gray-500">Address</span><span className="text-right max-w-[200px]">{selected.address}</span></div>}
              {selected.source && <div className="flex justify-between"><span className="text-gray-500">Source</span><span>{selected.source}</span></div>}
              {selected.notes && <div className="flex justify-between items-start"><span className="text-gray-500">Notes</span><span className="text-right max-w-[200px]">{selected.notes}</span></div>}
              <div className="flex justify-between"><span className="text-gray-500">Added</span><span>{formatDate(selected.createdAt)}</span></div>
            </div>

            <div className="flex flex-col gap-1.5">
              <label className="text-sm font-medium text-gray-700">Update Status</label>
              <div className="flex gap-2 flex-wrap">
                {statusOptions.map(s => (
                  <button key={s} onClick={() => setStatusUpdate(s)}
                    className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors border ${statusUpdate === s ? "border-blue-600 bg-blue-600 text-white" : "border-gray-200 text-gray-600 hover:border-blue-400"}`}>
                    {s}
                  </button>
                ))}
              </div>
              {statusUpdate !== selected.status && (
                <Button size="sm" className="mt-1" onClick={() => updateStatus.mutate({ id: selected.id, status: statusUpdate })} isLoading={updateStatus.isPending}>
                  Update to {statusUpdate}
                </Button>
              )}
            </div>

            <div className="flex justify-between pt-1">
              <Button variant="danger" size="sm" onClick={() => { if (confirm("Delete this lead?")) deleteLead.mutate(selected.id); }} isLoading={deleteLead.isPending}>Delete</Button>
              <Button variant="outline" size="sm" onClick={() => setSelected(null)}>Close</Button>
            </div>
          </div>
        )}
      </Modal>

      {/* Add Lead Modal */}
      <Modal isOpen={showAdd} onClose={() => setShowAdd(false)} title="Add New Lead">
        <div className="space-y-4">
          <div className="grid grid-cols-2 gap-3">
            <Input label="First Name *" value={form.firstName} onChange={e => setForm(f => ({ ...f, firstName: e.target.value }))} />
            <Input label="Last Name *" value={form.lastName} onChange={e => setForm(f => ({ ...f, lastName: e.target.value }))} />
          </div>
          <Input label="Phone *" value={form.phone} onChange={e => setForm(f => ({ ...f, phone: e.target.value }))} />
          <Input label="Email" type="email" value={form.email} onChange={e => setForm(f => ({ ...f, email: e.target.value }))} />
          <Input label="Address" value={form.address} onChange={e => setForm(f => ({ ...f, address: e.target.value }))} />
          <Input label="Source (e.g. Facebook, Referral)" value={form.source} onChange={e => setForm(f => ({ ...f, source: e.target.value }))} />
          <div className="flex flex-col gap-1.5">
            <label className="text-sm font-medium text-gray-700">Notes</label>
            <textarea className="border rounded-lg px-3 py-2 text-sm resize-none h-16 focus:outline-none focus:ring-2 focus:ring-blue-500"
              value={form.notes} onChange={e => setForm(f => ({ ...f, notes: e.target.value }))} />
          </div>
          <div className="flex justify-end gap-2">
            <Button variant="outline" onClick={() => setShowAdd(false)}>Cancel</Button>
            <Button onClick={() => addLead.mutate()} isLoading={addLead.isPending} disabled={!form.firstName || !form.lastName || !form.phone}>Add Lead</Button>
          </div>
        </div>
      </Modal>
    </div>
  );
}
