"use client";

import * as React from "react";
import Link from "next/link";
import { useSession } from "next-auth/react";
import { format } from "date-fns";
import {
  ChevronLeft,
  Eye,
  FilterX,
  Pencil,
  RefreshCw,
  ShieldCheck,
  XCircle,
} from "lucide-react";
import type { Deal } from "@/api/endpoints/deals-api";
import { useGetAllUsersQuery, useGetRolesQuery, useGetPipelinesQuery } from "@/api/endpoints";
import { useGetClosedLeadTagsQuery } from "@/api/endpoints/deal-meta-api";
import { useGetProfileQuery } from "@/api/endpoints/auth-api";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { SearchInput } from "@/components/ui/search-input";
import { Spinner } from "@/components/ui/spinner";
import {
  CompactFilterPopover,
  compactFilterSectionIsActive,
  type CompactFilterSection,
} from "@/components/shared/compact-filter-popover";
import { DEALS_FILTER_CLEAR_BUTTON_CLASS } from "@/components/deals/deals-filter-styles";
import { cn } from "@/lib/utils";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { useClosedLostLeadsPagedQuery } from "@/features/closed-lost-leads/hooks/use-closed-lost-leads-paged-query";
import {
  EditClosedLostLeadDialog,
  leadNeedsClosedLostDetails,
} from "@/components/leads/edit-closed-lost-lead-dialog";
import { useAuthToken } from "@/hooks/use-auth-token";
import { useUrlPagination } from "@/hooks/use-url-pagination";
import { pickRoleIdFromOrgRoles } from "@/components/deals/contributor-user-picker";
import { resolveLeadStageDisplayName, flattenPipelineStages } from "@/lib/deal-stage-labels";
import {
  canViewClosedLostLeads,
  hasPermission,
  isAccountExecutiveRoleName,
  isBdrRoleName,
  type PermissionSource,
} from "@/lib/permissions";

const PAGE_SIZE = 25;

type AssigneeUser = {
  id: string;
  name?: string | null;
  email?: string | null;
  role?: { id?: string; name?: string | null } | null;
};

function normalizeRoleLabel(name?: string | null): string {
  return (name ?? "").trim().toLowerCase().replace(/\s+/g, " ");
}

function userMatchesAeAssignmentPool(user: AssigneeUser, aeRoleId?: string): boolean {
  if (aeRoleId && user.role?.id === aeRoleId) return true;
  const role = normalizeRoleLabel(user.role?.name);
  if (!role) return false;
  if (isAccountExecutiveRoleName(role)) return true;
  if (role.includes("account executive")) return true;
  return role === "ae" || role.endsWith(" ae") || role.startsWith("ae ");
}

function userMatchesBdrAssignmentPool(user: AssigneeUser, bdrRoleId?: string): boolean {
  if (bdrRoleId && user.role?.id === bdrRoleId) return true;
  const role = normalizeRoleLabel(user.role?.name);
  if (!role) return false;
  if (isBdrRoleName(role)) return true;
  if (role.includes("business development")) return true;
  return role === "bdr" || role.includes(" bdr") || role.startsWith("bdr ");
}

function buildAssigneeFilterOptions(
  users: AssigneeUser[],
  match: (user: AssigneeUser) => boolean,
): { value: string; label: string }[] {
  const matched = users.filter(match);
  const pool = matched.length > 0 ? matched : users;
  const sorted = [...pool].sort((a, b) =>
    (a.name || a.email || a.id).localeCompare(b.name || b.email || b.id),
  );
  return sorted.map((u) => ({
    value: u.id,
    label: u.name || u.email || u.id,
  }));
}

const MULTILINE_CELL =
  "whitespace-normal align-top py-4 max-1400:py-2 max-1400:px-2 max-1400:text-xs";
const ACTIONS_HEAD = "w-[1%] whitespace-nowrap text-right max-1400:px-2";
const ACTIONS_CELL =
  "w-[1%] whitespace-nowrap align-top py-4 max-1400:py-2 max-1400:px-2";
const TABLE_HEAD = "max-1400:px-2 max-1400:text-[9px] max-1400:h-10";
const TABLE_TEXT = "text-sm max-1400:text-xs";

function formatDate(d?: string | null) {
  if (!d) return "—";
  const dt = new Date(d);
  return Number.isNaN(dt.getTime()) ? "—" : format(dt, "MMM d, yyyy");
}

function ReasonCell({
  text,
  onAddDetails,
  canEdit,
}: {
  text?: string | null;
  onAddDetails?: () => void;
  canEdit?: boolean;
}) {
  const trimmed = text?.trim() ?? "";
  if (!trimmed) {
    if (canEdit && onAddDetails) {
      return (
        <Button
          type="button"
          variant="outline"
          size="sm"
          className="h-8 border-amber-200 bg-amber-50/80 text-xs font-medium text-amber-800 hover:bg-amber-100 hover:text-amber-900 max-1400:h-7 max-1400:px-2 max-1400:text-[10px]"
          onClick={onAddDetails}
        >
          <Pencil className="mr-1.5 size-3.5 max-1400:mr-1 max-1400:size-3" />
          Add reason & tags
        </Button>
      );
    }
    return <span className="text-sm text-gray-400 max-1400:text-xs">No reason recorded</span>;
  }
  return (
    <p
      className="max-w-md text-sm leading-relaxed text-gray-800 line-clamp-4 max-1400:max-w-sm max-1400:text-xs max-1400:leading-snug"
      title={trimmed}
    >
      {trimmed}
    </p>
  );
}

function TagsCell({ tags }: { tags?: { id: string; name: string }[] }) {
  if (!tags?.length) {
    return <span className="text-sm text-gray-300 max-1400:text-xs">—</span>;
  }
  return (
    <div className="flex flex-wrap gap-1">
      {tags.map((tag) => (
        <Badge
          key={tag.id}
          variant="secondary"
          className="whitespace-nowrap bg-slate-100 text-slate-700 hover:bg-slate-100 max-1400:px-1.5 max-1400:py-0 max-1400:text-[10px]"
        >
          {tag.name}
        </Badge>
      ))}
    </div>
  );
}

function ClosedLostFilterTooltip({
  label,
  children,
  className,
}: {
  label: string;
  children: React.ReactNode;
  className?: string;
}) {
  return (
    <Tooltip>
      <TooltipTrigger asChild>
        <div className={cn("min-w-0", className)}>{children}</div>
      </TooltipTrigger>
      <TooltipContent side="bottom" sideOffset={6}>
        {label}
      </TooltipContent>
    </Tooltip>
  );
}

function ClosedLostPageNumbers({
  page,
  totalPages,
  setPage,
}: {
  page: number;
  totalPages: number;
  setPage: (n: number) => void;
}) {
  if (totalPages <= 1) return null;

  const windowSize = Math.min(5, totalPages);
  const pageNumbers = Array.from({ length: windowSize }, (_, i) => {
    if (totalPages <= 5) return i + 1;
    if (page <= 3) return i + 1;
    if (page >= totalPages - 2) return totalPages - 4 + i;
    return page - 2 + i;
  });

  return (
    <div className="flex items-center gap-1">
      {pageNumbers.map((pageNum) => (
        <Button
          key={pageNum}
          type="button"
          variant={page === pageNum ? "paginationPageCurrent" : "outline"}
          size="page"
          onClick={() => setPage(pageNum)}
        >
          {pageNum.toLocaleString()}
        </Button>
      ))}
    </div>
  );
}

export function ClosedLostLeadsPage() {
  const { data: nextAuthSession } = useSession();
  const { token } = useAuthToken();
  const backendUser =
    (nextAuthSession as { backendUser?: PermissionSource } | null)?.backendUser ??
    null;
  const { data: profile } = useGetProfileQuery(undefined, { skip: !token });
  const permissionSource: PermissionSource = backendUser ?? profile ?? null;
  const canViewPage = canViewClosedLostLeads(permissionSource);
  const canUpdateLeads = hasPermission(permissionSource, "UPDATE", "LEAD");

  const [searchInput, setSearchInput] = React.useState("");
  const [debouncedSearch, setDebouncedSearch] = React.useState("");

  const [assignAeFilterId, setAssignAeFilterId] = React.useState("all");
  const [assignBdrFilterId, setAssignBdrFilterId] = React.useState("all");
  const [leadOwnerFilterId, setLeadOwnerFilterId] = React.useState("all");
  const [editingLead, setEditingLead] = React.useState<Deal | null>(null);
  const [editDialogOpen, setEditDialogOpen] = React.useState(false);
  const autoPromptKeyRef = React.useRef<string | null>(null);

  const { page, setPage, limit: pageSize } = useUrlPagination(PAGE_SIZE);

  const { data: closedLeadTagCatalog = [] } = useGetClosedLeadTagsQuery(
    undefined,
    { skip: !canViewPage },
  );
  const { data: allUsers = [], isSuccess: allUsersLoaded } = useGetAllUsersQuery(
    undefined,
    { skip: !canViewPage },
  );
  const { data: orgRoles = [] } = useGetRolesQuery(undefined, {
    skip: !canViewPage,
  });
  const { data: pipelines = [] } = useGetPipelinesQuery(undefined, {
    skip: !canViewPage,
  });

  const pipelineStages = React.useMemo(
    () => pipelines.flatMap((p) => flattenPipelineStages(p.stages ?? [])),
    [pipelines],
  );

  const aeRoleId = React.useMemo(
    () => pickRoleIdFromOrgRoles(orgRoles, ["ae", "account executive"]),
    [orgRoles],
  );
  const bdrRoleId = React.useMemo(
    () =>
      pickRoleIdFromOrgRoles(orgRoles, [
        "bdr",
        "business development",
        "business development representative",
      ]),
    [orgRoles],
  );

  const assignAeFilterOptions = React.useMemo(
    () =>
      buildAssigneeFilterOptions(allUsers, (u) =>
        userMatchesAeAssignmentPool(u, aeRoleId),
      ),
    [allUsers, aeRoleId],
  );

  const assignBdrFilterOptions = React.useMemo(
    () =>
      buildAssigneeFilterOptions(allUsers, (u) =>
        userMatchesBdrAssignmentPool(u, bdrRoleId),
      ),
    [allUsers, bdrRoleId],
  );

  const leadOwnerFilterOptions = React.useMemo(() => {
    const aeUsers = allUsers.filter((u) =>
      isAccountExecutiveRoleName(u.role?.name),
    );
    const sorted = [...aeUsers].sort((a, b) =>
      (a.name || a.email || a.id).localeCompare(b.name || b.email || b.id),
    );
    return sorted.map((u) => ({
      value: u.id,
      label: u.name || u.email || u.id,
    }));
  }, [allUsers]);

  React.useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedSearch(searchInput.trim());
    }, 300);
    return () => clearTimeout(timer);
  }, [searchInput]);

  React.useEffect(() => {
    setPage(1);
  }, [debouncedSearch, assignAeFilterId, assignBdrFilterId, leadOwnerFilterId, setPage]);

  const listParams = React.useMemo(
    () => ({
      ...(debouncedSearch ? { search: debouncedSearch } : {}),
      ...(leadOwnerFilterId !== "all" ? { userId: leadOwnerFilterId } : {}),
      ...(assignAeFilterId !== "all" ? { aeUserId: assignAeFilterId } : {}),
      ...(assignBdrFilterId !== "all" ? { bdrUserId: assignBdrFilterId } : {}),
      page,
      limit: pageSize,
    }),
    [debouncedSearch, leadOwnerFilterId, assignAeFilterId, assignBdrFilterId, page, pageSize],
  );

  const hasActiveFilters = Boolean(
    debouncedSearch ||
      leadOwnerFilterId !== "all" ||
      assignAeFilterId !== "all" ||
      assignBdrFilterId !== "all",
  );

  const handleClearFilters = React.useCallback(() => {
    setSearchInput("");
    setDebouncedSearch("");
    setLeadOwnerFilterId("all");
    setAssignAeFilterId("all");
    setAssignBdrFilterId("all");
  }, []);

  const compactFilterSections = React.useMemo((): CompactFilterSection[] => {
    const peopleGroup = "People";
    return [
      {
        id: "lead-owner",
        label: "Lead Owner",
        value: leadOwnerFilterId,
        options: [
          { value: "all", label: "All Lead Owners" },
          ...leadOwnerFilterOptions,
        ],
        onValueChange: setLeadOwnerFilterId,
        group: peopleGroup,
        disabled: !allUsersLoaded,
        loading: !allUsersLoaded,
      },
      {
        id: "assign-ae",
        label: "Assigned AE",
        value: assignAeFilterId,
        options: [
          { value: "all", label: "All Assign AE" },
          ...assignAeFilterOptions,
        ],
        onValueChange: setAssignAeFilterId,
        group: peopleGroup,
        disabled: !allUsersLoaded,
        loading: !allUsersLoaded,
      },
      {
        id: "assign-bdr",
        label: "Assigned BDR",
        value: assignBdrFilterId,
        options: [
          { value: "all", label: "All Assign BDR" },
          ...assignBdrFilterOptions,
        ],
        onValueChange: setAssignBdrFilterId,
        group: peopleGroup,
        disabled: !allUsersLoaded,
        loading: !allUsersLoaded,
      },
    ];
  }, [
    leadOwnerFilterId,
    assignAeFilterId,
    assignBdrFilterId,
    leadOwnerFilterOptions,
    assignAeFilterOptions,
    assignBdrFilterOptions,
    allUsersLoaded,
  ]);

  const compactFiltersTooltip = React.useMemo(() => {
    const active = compactFilterSections
      .filter(compactFilterSectionIsActive)
      .map((section) => section.label);
    if (active.length === 0) return "Lead filters";
    return `Active filters: ${active.join(", ")}`;
  }, [compactFilterSections]);

  const {
    data: pageResult,
    isLoading,
    isFetching,
    refetch,
  } = useClosedLostLeadsPagedQuery(listParams, {
    enabled: canViewPage,
    staleTime: 60_000,
    gcTime: 5 * 60_000,
  });

  const leads = pageResult?.items ?? [];
  const total = pageResult?.total ?? 0;
  const totalPages = total > 0 ? Math.ceil(total / pageSize) : 0;
  const rangeStart = total > 0 ? (page - 1) * pageSize + 1 : 0;
  const rangeEnd = total > 0 ? Math.min(page * pageSize, total) : 0;

  const closedLeadTagOptions = React.useMemo(
    () =>
      closedLeadTagCatalog.map((t) => ({
        value: t.name,
        label: t.name,
      })),
    [closedLeadTagCatalog],
  );

  const openEditDialog = React.useCallback((lead: Deal) => {
    setEditingLead(lead);
    setEditDialogOpen(true);
  }, []);



  if (!canViewPage) {
    return (
      <div className="p-6">
        <div className="mx-auto max-w-md rounded-2xl border bg-white p-8 text-center shadow-sm">
          <div className="mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-full bg-red-100">
            <ShieldCheck className="size-7 text-red-600" />
          </div>
          <h1 className="text-xl font-semibold">Access restricted</h1>
          <p className="mt-2 text-sm text-muted-foreground">
            You need READ permission on Closed Lost Leads to view this page.
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6 p-6 max-1400:space-y-4 max-1400:p-4">
      <div className="flex flex-col gap-3">
        <Link
          href="/leads"
          className="inline-flex w-fit items-center gap-1 text-xs font-medium text-muted-foreground transition-colors hover:text-accent max-1400:text-[11px]"
        >
          <ChevronLeft className="size-3.5 max-1400:size-3" />
          Back to Leads
        </Link>
        <div className="flex flex-col gap-4">
          <div className="flex flex-col gap-1">
            <h1 className="font-['Lexend'] text-2xl font-extrabold tracking-tight text-[#101828] sm:text-3xl max-1400:text-xl max-1400:sm:text-2xl">
              Closed Lost Leads
            </h1>
            <p className="text-sm text-[#475467] max-1400:text-xs">
              All leads in a closed-lost stage with their reason and extra
              content tags.
            </p>
          </div>
          <TooltipProvider delayDuration={300}>
            <div className="flex w-full min-w-0 flex-col gap-2">
              <div className="flex w-full min-w-0 flex-col items-stretch justify-between gap-4 min-[1440px]:gap-3 lg:flex-row lg:items-center">
                <ClosedLostFilterTooltip
                  label="Search name, phone, email, reason"
                  className="flex-1 w-full max-[1499px]:max-w-[200px] min-[1500px]:max-w-[min(100%,24rem)]"
                >
                  <SearchInput
                    wrapperClassName="w-full"
                    value={searchInput}
                    onChange={(e) => setSearchInput(e.target.value)}
                    placeholder="Search name, phone, email, reason..."
                    className="h-7 max-[1499px]:text-[11px] min-[1500px]:h-9 min-[1500px]:text-[13px] rounded-lg min-[1500px]:rounded-xl"
                    aria-label="Search name, phone, email, reason"
                  />
                </ClosedLostFilterTooltip>

                <div className="flex min-w-0 flex-1 flex-wrap items-center gap-1.5 min-[1500px]:gap-2 lg:justify-end">
                  <ClosedLostFilterTooltip label={compactFiltersTooltip} className="shrink-0">
                    <CompactFilterPopover
                      sections={compactFilterSections}
                      triggerClassName={DEALS_FILTER_CLEAR_BUTTON_CLASS}
                      ariaLabel="Closed lost lead filters"
                    />
                  </ClosedLostFilterTooltip>

                  {hasActiveFilters && (
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <Button
                          type="button"
                          variant="outline"
                          className={DEALS_FILTER_CLEAR_BUTTON_CLASS}
                          onClick={handleClearFilters}
                          aria-label="Clear filters"
                        >
                          <FilterX className="size-4" aria-hidden />
                        </Button>
                      </TooltipTrigger>
                      <TooltipContent side="bottom" sideOffset={6}>
                        Clear filters
                      </TooltipContent>
                    </Tooltip>
                  )}

                  <Button
                    variant="outline"
                    size="sm"
                    className="h-7 min-h-7 px-2.5 text-[11px] min-[1500px]:h-9 min-[1500px]:px-3 min-[1500px]:text-xs"
                    onClick={() => refetch()}
                    disabled={isFetching}
                  >
                    <RefreshCw
                      className={`mr-1.5 size-3 ${isFetching ? "animate-spin" : ""}`}
                    />
                    Refresh
                  </Button>
                </div>
              </div>
            </div>
          </TooltipProvider>
        </div>
      </div>

      <div className="flex flex-wrap items-center gap-x-3 gap-y-1 rounded-xl border bg-white px-3 py-2 text-xs text-muted-foreground max-1400:gap-x-2 max-1400:rounded-lg max-1400:px-2.5 max-1400:py-1.5 max-1400:text-[11px]">
        <XCircle className="size-3.5 shrink-0 text-red-500 max-1400:size-3" />
        <span className="leading-snug">
          {isLoading
            ? "Loading closed-lost leads…"
            : total > 0
              ? `${total.toLocaleString()} closed-lost lead${total === 1 ? "" : "s"}`
              : "No closed-lost leads match the current filters."}
        </span>
        {total > 0 && totalPages > 0 ? (
          <>
            <span className="hidden text-border sm:inline">|</span>
            <span className="font-medium text-gray-700 max-1400:font-normal">
              Page {page.toLocaleString()} of {totalPages.toLocaleString()}
            </span>
          </>
        ) : null}
      </div>

      {isLoading ? (
        <div className="flex h-40 items-center justify-center">
          <Spinner />
        </div>
      ) : leads.length === 0 ? (
        <div className="rounded-2xl border bg-white p-10 text-center">
          <div className="mx-auto mb-3 flex h-12 w-12 items-center justify-center rounded-full bg-slate-100">
            <XCircle className="size-6 text-slate-500" />
          </div>
          <div className="text-lg font-medium">
            {debouncedSearch ||
            leadOwnerFilterId !== "all" ||
            assignAeFilterId !== "all" ||
            assignBdrFilterId !== "all"
              ? "No matches found"
              : "No closed-lost leads"}
          </div>
          <p className="mt-1 text-sm text-muted-foreground">
            {debouncedSearch
              ? `No leads match “${debouncedSearch}”.`
              : leadOwnerFilterId !== "all" ||
                  assignAeFilterId !== "all" ||
                  assignBdrFilterId !== "all"
                ? "No closed-lost leads match the selected filters."
                : "Leads appear here after they are moved to a closed-lost stage."}
          </p>
        </div>
      ) : (
        <div className="space-y-3">
          <Table className="min-w-[1400px] max-1400:min-w-[1180px] max-1400:text-[11px]">
            <TableHeader className="sticky top-0 z-10">
              <TableRow className="cursor-default hover:bg-transparent">
                <TableHead className={`min-w-[140px] ${TABLE_HEAD} max-1400:min-w-[110px]`}>Lead name</TableHead>
                <TableHead className={`min-w-[160px] ${TABLE_HEAD} max-1400:min-w-[130px]`}>Lead ID</TableHead>
                <TableHead className={`min-w-[120px] ${TABLE_HEAD} max-1400:min-w-[95px]`}>Phone</TableHead>
                <TableHead className={`min-w-[180px] ${TABLE_HEAD} max-1400:min-w-[140px]`}>Email</TableHead>
                <TableHead className={`min-w-[120px] ${TABLE_HEAD} max-1400:min-w-[95px]`}>Owner</TableHead>
                <TableHead className={`min-w-[100px] ${TABLE_HEAD} max-1400:min-w-[80px]`}>Team</TableHead>
                <TableHead className={`min-w-[120px] ${TABLE_HEAD} max-1400:min-w-[100px]`}>Stage</TableHead>
                <TableHead className={`min-w-[280px] ${TABLE_HEAD} max-1400:min-w-[200px]`}>Closed reason</TableHead>
                <TableHead className={`min-w-[100px] ${TABLE_HEAD} max-1400:min-w-[85px]`}>Closed</TableHead>
                <TableHead className={`min-w-[100px] ${TABLE_HEAD} max-1400:min-w-[85px]`}>Created</TableHead>
                <TableHead className={ACTIONS_HEAD}>Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {leads.map((lead: Deal) => (
                <TableRow key={lead.id} className="cursor-default">
                  <TableCell className={MULTILINE_CELL}>
                    <div
                      className="font-medium text-gray-900 max-1400:text-xs"
                      title={lead.customerName ?? undefined}
                    >
                      {lead.customerName || "—"}
                    </div>
                  </TableCell>
                  <TableCell className={MULTILINE_CELL}>
                    <div
                      className="break-all text-sm text-gray-700 max-1400:text-xs"
                      title={lead.leadId ?? undefined}
                    >
                      {lead.leadId || "—"}
                    </div>
                  </TableCell>
                  <TableCell className={`${MULTILINE_CELL} text-sm text-gray-800`}>
                    {lead.phone || "—"}
                  </TableCell>
                  <TableCell className={MULTILINE_CELL}>
                    <div
                      className="break-all text-sm text-gray-700 max-1400:text-xs"
                      title={lead.email ?? undefined}
                    >
                      {lead.email || "—"}
                    </div>
                  </TableCell>
                  <TableCell className={`${MULTILINE_CELL} text-sm text-gray-800`}>
                    {lead.owner?.name || "—"}
                  </TableCell>
                  <TableCell className={`${MULTILINE_CELL} text-sm text-gray-700`}>
                    {lead.team || "—"}
                  </TableCell>
                  <TableCell className={`${TABLE_TEXT} text-gray-700`}>
                    {resolveLeadStageDisplayName(lead, pipelineStages)}
                  </TableCell>
                  <TableCell className={MULTILINE_CELL}>
                    <ReasonCell
                      text={lead.lostReason}
                      canEdit={canUpdateLeads}
                      onAddDetails={() => openEditDialog(lead)}
                    />
                  </TableCell>
                  <TableCell className={`${TABLE_TEXT} text-gray-600`}>
                    {formatDate(lead.updatedAt)}
                  </TableCell>
                  <TableCell className={`${TABLE_TEXT} text-gray-600`}>
                    {formatDate(lead.createdDate || lead.createdAt)}
                  </TableCell>
                  <TableCell className={ACTIONS_CELL}>
                    <div className="flex items-center justify-end gap-1">
                      {canUpdateLeads &&
                      leadNeedsClosedLostDetails(lead) ? (
                        <Button
                          size="sm"
                          variant="ghost"
                          className="h-8 shrink-0 px-2.5 text-xs text-amber-800 hover:bg-amber-50 hover:text-amber-900 max-1400:h-7 max-1400:px-2 max-1400:text-[10px]"
                          onClick={() => openEditDialog(lead)}
                          aria-label={`Add closed-lost details for ${lead.customerName ?? lead.leadId ?? lead.id}`}
                        >
                          <Pencil className="mr-1 size-3.5 max-1400:mr-0.5 max-1400:size-3" />
                          Edit
                        </Button>
                      ) : null}
                      <Button
                        size="sm"
                        variant="ghost"
                        className="h-8 shrink-0 px-2.5 text-xs max-1400:h-7 max-1400:px-2 max-1400:text-[10px]"
                        asChild
                      >
                        <Link
                          href={`/leads/${lead.id}`}
                          aria-label={`View lead ${lead.customerName ?? lead.leadId ?? lead.id}`}
                        >
                          <Eye className="mr-1 size-3.5 max-1400:mr-0.5 max-1400:size-3" />
                          View
                        </Link>
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>

          {total > 0 ? (
            <div className="flex flex-col gap-3 border-t border-border/60 pt-3 sm:flex-row sm:items-center sm:justify-between max-1400:gap-2 max-1400:pt-2">
              <span className="text-xs text-muted-foreground max-1400:text-[11px]">
                Showing {rangeStart.toLocaleString()}–{rangeEnd.toLocaleString()}{" "}
                of {total.toLocaleString()}
              </span>
              {totalPages > 1 ? (
                <div className="flex flex-wrap items-center gap-2">
                  <Button
                    variant="outline"
                    size="pagination"
                    onClick={() => setPage(Math.max(1, page - 1))}
                    disabled={page <= 1}
                  >
                    Previous
                  </Button>
                  <ClosedLostPageNumbers
                    page={page}
                    totalPages={totalPages}
                    setPage={setPage}
                  />
                  <Button
                    variant="outline"
                    size="pagination"
                    onClick={() => setPage(Math.min(totalPages, page + 1))}
                    disabled={page >= totalPages}
                  >
                    Next
                  </Button>
                </div>
              ) : null}
            </div>
          ) : null}
        </div>
      )}

      <EditClosedLostLeadDialog
        lead={editingLead}
        open={editDialogOpen}
        onOpenChange={(open) => {
          setEditDialogOpen(open);
          if (!open) setEditingLead(null);
        }}
      />
    </div>
  );
}
