"use client";

import { useState } from "react";
import { useQuery } 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 { formatDate } from "@/lib/utils";
import api from "@/lib/api";
import type { Lead } from "@/types";

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

export default function LeadsPage() {
  const [search, setSearch] = useState("");

  const { data, isLoading, refetch } = useQuery<Lead[]>({
    queryKey: ["leads", search],
    queryFn: async () => {
      const params = new URLSearchParams({ limit: "50" });
      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 leads = data ?? [];

  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>
        <Button onClick={() => refetch()} variant="outline" size="sm">
          <RefreshCw size={14} className="mr-1.5" /> Refresh
        </Button>
      </div>

      {/* Status summary */}
      <div className="flex gap-3 flex-wrap">
        {Object.entries(statusVariant).map(([status]) => {
          const count = leads.filter(l => l.status === status).length;
          return count > 0 ? (
            <div key={status} className="bg-white border rounded-lg px-3 py-2 text-center min-w-[80px]">
              <p className="text-lg font-bold text-gray-800">{count}</p>
              <p className="text-xs text-gray-500">{status}</p>
            </div>
          ) : null;
        })}
      </div>

      <Card>
        <CardHeader>
          <div className="flex items-center justify-between gap-4">
            <CardTitle>All Leads ({leads.length})</CardTitle>
            <Input
              placeholder="Search by name or phone..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="max-w-xs"
            />
          </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>Assigned To</Th>
                <Th>Added</Th>
              </TableRow>
            </TableHead>
            <TableBody>
              {isLoading ? (
                <TableRow><Td colSpan={7} className="text-center py-8 text-gray-400">Loading...</Td></TableRow>
              ) : leads.length === 0 ? (
                <EmptyState colSpan={7} message="No leads yet" icon={<UserPlus size={24} />} />
              ) : (
                leads.map((lead) => (
                  <TableRow key={lead.id}>
                    <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-500">
                      {lead.assignedTo
                        ? `${lead.assignedTo.firstName} ${lead.assignedTo.lastName}`
                        : "—"}
                    </Td>
                    <Td className="text-gray-400 text-sm">{formatDate(lead.createdAt)}</Td>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
}
