"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Card } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { PaginationControl } from "@/components/ui/pagination-control";
import { LEAD_STATUSES, LEAD_STATUS_STYLES } from "@/lib/leads/constants";
import type { Lead } from "@/lib/types";
import { DeleteLeadDialog } from "./delete-lead-dialog";

type LeadRow = Lead & { source?: { name: string } | null };

const ALL = "__all__";

/**
 * Server-paginated leads table. Filters/pagination live in the URL — the server
 * page does the filtering + .range(); this component only renders the current
 * page and pushes new query params on filter/page change.
 */
export function LeadsTable({
  leads,
  total,
  page = 1,
  pageSize = leads.length || 1,
  filters,
}: {
  leads: LeadRow[];
  total?: number;
  page?: number;
  pageSize?: number;
  /** When provided, renders the URL-driven filter bar + server pager. */
  filters?: { q: string; status: string; country: string };
}) {
  const router = useRouter();
  const [q, setQ] = useState(filters?.q ?? "");
  const [status, setStatus] = useState(filters?.status || ALL);
  const [country, setCountry] = useState(filters?.country ?? "");

  // Keep state in sync if filters prop changes from URL/navigation
  useEffect(() => {
    if (filters) {
      setQ(filters.q ?? "");
      setStatus(filters.status || ALL);
      setCountry(filters.country ?? "");
    }
  }, [filters?.q, filters?.status, filters?.country]);

  // Debounce pushing updated search params to URL when typing or selecting filters
  useEffect(() => {
    if (!filters) return;

    const currentQ = filters.q ?? "";
    const currentStatus = filters.status || ALL;
    const currentCountry = filters.country ?? "";

    if (q === currentQ && status === currentStatus && country === currentCountry) {
      return;
    }

    const timer = setTimeout(() => {
      const p = new URLSearchParams();
      if (q.trim()) p.set("q", q.trim());
      if (status !== ALL) p.set("status", status);
      if (country.trim()) p.set("country", country.trim());
      const queryStr = p.toString();
      router.push(queryStr ? `/leads?${queryStr}` : "/leads");
    }, 300);

    return () => clearTimeout(timer);
  }, [q, status, country, filters, router]);

  function apply() {
    const p = new URLSearchParams();
    if (q.trim()) p.set("q", q.trim());
    if (status !== ALL) p.set("status", status);
    if (country.trim()) p.set("country", country.trim());
    router.push(p.toString() ? `/leads?${p}` : "/leads");
  }

  function reset() {
    setQ("");
    setStatus(ALL);
    setCountry("");
    router.push("/leads");
  }

  return (
    <div className="space-y-4">
      {filters && (
      <div className="flex flex-wrap items-end gap-3">
        <Input
          placeholder="Search name, phone, email…"
          value={q}
          onChange={(e) => setQ(e.target.value)}
          onKeyDown={(e) => e.key === "Enter" && apply()}
          className="h-9 w-64"
        />
        <Select value={status} onValueChange={setStatus}>
          <SelectTrigger className="h-9 w-44">
            <SelectValue placeholder="All statuses" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value={ALL}>All statuses</SelectItem>
            {LEAD_STATUSES.map((s) => (
              <SelectItem key={s} value={s}>
                {s}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
        <Input
          placeholder="Country"
          value={country}
          onChange={(e) => setCountry(e.target.value)}
          onKeyDown={(e) => e.key === "Enter" && apply()}
          className="h-9 w-40"
        />
        <Button onClick={apply} size="sm">Search</Button>
        <Button onClick={reset} size="sm" variant="ghost">Reset</Button>
      </div>
      )}

      <Card className="p-0">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="w-12">No</TableHead>
              <TableHead>Name</TableHead>
              <TableHead>Phone</TableHead>
              <TableHead>Email</TableHead>
              <TableHead>Country</TableHead>
              <TableHead>Status</TableHead>
              <TableHead>Created</TableHead>
              <TableHead className="text-right">Action</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {leads.length === 0 ? (
              <TableRow>
                <TableCell colSpan={8} className="py-10 text-center text-muted-foreground">
                  No leads match these filters.
                </TableCell>
              </TableRow>
            ) : (
              leads.map((lead, i) => (
                <TableRow key={lead.id}>
                  <TableCell className="text-muted-foreground">
                    {(page - 1) * pageSize + i + 1}
                  </TableCell>
                  <TableCell className="font-medium">
                    <Link href={`/leads/${lead.id}`} className="hover:text-brand-blue hover:underline">
                      {lead.full_name}
                    </Link>
                  </TableCell>
                  <TableCell>{lead.phone ?? "—"}</TableCell>
                  <TableCell>{lead.email ?? "—"}</TableCell>
                  <TableCell>{lead.country ?? "—"}</TableCell>
                  <TableCell>
                    <Badge className={LEAD_STATUS_STYLES[lead.lead_status] ?? "bg-muted text-foreground"}>
                      {lead.lead_status}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    {lead.created_at ? new Date(lead.created_at).toLocaleDateString() : "—"}
                  </TableCell>
                  <TableCell className="text-right">
                    <div className="flex items-center justify-end gap-2">
                      <Button asChild variant="outline" size="sm">
                        <Link href={`/leads/${lead.id}`}>View</Link>
                      </Button>
                      <DeleteLeadDialog leadId={lead.id} leadName={lead.full_name} />
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </Card>

      {filters && (
        <PaginationControl page={page} pageSize={pageSize} total={total ?? leads.length} />
      )}
    </div>
  );
}
