"use client";

import Link from "next/link";
import { Lead } from "@/db/schema";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { formatDistanceToNow } from "date-fns";
import { it } from "date-fns/locale";
import { LEAD_STAGES } from "@/lib/lead-validators";

const STAGE_COLOR: Record<string, string> = {
  contacted: "bg-blue-100 text-blue-800",
  qualified: "bg-purple-100 text-purple-800",
  proposal_sent: "bg-amber-100 text-amber-800",
  negotiating: "bg-orange-100 text-orange-800",
  won: "bg-green-100 text-green-800",
  lost: "bg-red-100 text-red-800",
};

export function LeadTable({ leads }: { leads: Lead[] }) {
  return (
    <div className="border rounded-lg overflow-hidden bg-white">
      <Table>
        <TableHeader>
          <TableRow>
            <TableHead>Nome</TableHead>
            <TableHead>Email</TableHead>
            <TableHead>Azienda</TableHead>
            <TableHead>Stato</TableHead>
            <TableHead>Ultimo Contatto</TableHead>
            <TableHead>Prossima Azione</TableHead>
            <TableHead></TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {leads.map((lead) => (
            <TableRow key={lead.id}>
              <TableCell className="font-medium">
                <Link href={`/admin/leads/${lead.id}`} className="hover:underline">
                  {lead.name}
                </Link>
              </TableCell>
              <TableCell>{lead.email || "—"}</TableCell>
              <TableCell>{lead.company || "—"}</TableCell>
              <TableCell>
                <Badge className={STAGE_COLOR[lead.status as keyof typeof STAGE_COLOR] || ""}>
                  {lead.status.replace(/_/g, " ")}
                </Badge>
              </TableCell>
              <TableCell>
                {lead.last_contact_date
                  ? formatDistanceToNow(new Date(lead.last_contact_date), {
                      addSuffix: true,
                      locale: it,
                    })
                  : "—"}
              </TableCell>
              <TableCell className="text-sm">{lead.next_action || "—"}</TableCell>
              <TableCell>
                <Button variant="ghost" size="sm" asChild>
                  <Link href={`/admin/leads/${lead.id}`}>Dettagli</Link>
                </Button>
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
      {leads.length === 0 && (
        <div className="text-center py-8 text-gray-500">Nessun lead trovato</div>
      )}
    </div>
  );
}
