"use client";

import * as React from "react";
import { Deal, Stage } from "./types";
import { DealListViewProps } from "@/types/deals";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Can } from "@/components/providers/ability-provider";
import { Trash2, PencilLine, Eye, MoreHorizontal } from "lucide-react";
import { cn } from "@/lib/utils";
import { formatTeamLabelForUi } from "@/lib/deal-display";
import { Spinner } from "@/components/ui/spinner";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";

function initials(name?: string) {
  if (!name) return "?";
  return name
    .split(/\s+/)
    .map((w) => w[0])
    .join("")
    .slice(0, 2)
    .toUpperCase();
}

function avatarColor(name?: string) {
  const colors = [
    "#6C63FF",
    "#22C55E",
    "#F59E0B",
    "#EF4444",
    "#3B82F6",
    "#EC4899",
    "#8B5CF6",
  ];
  if (!name) return colors[0];
  return colors[name.charCodeAt(0) % colors.length];
}

function formatCreatedDate(deal: Deal): string {
  const raw = deal.createdDate || deal.createdAt;
  if (!raw) return "—";
  const d = new Date(raw);
  if (Number.isNaN(d.getTime())) return String(raw);
  return d.toLocaleDateString(undefined, {
    year: "numeric",
    month: "short",
    day: "numeric",
  });
}

export function DealListView({
  deals,
  stages = [],
  selectAllAriaLabel = "Select all leads",
  emptyTitle = "No matching leads found",
  emptySubtitle = "Try adjusting your search or filters",
  onOpen,
  onEdit,
  onDelete,
  sortCol,
  sortDir,
  onSort,
  canSubject = "deal",
  selectedIds,
  onSelectId,
  onSelectAll,
  listInfiniteLoad,
}: DealListViewProps & {
  selectedIds?: Set<string>;
  onSelectId?: (id: string, checked: boolean) => void;
  onSelectAll?: (checked: boolean) => void;
}) {
  const stickyHeadClass =
    "sticky top-0 z-20 bg-white border-b border-gray-200";
  const loadMoreSentinelRef = React.useRef<HTMLDivElement | null>(null);

  React.useEffect(() => {
    if (!listInfiniteLoad) return;
    const el = loadMoreSentinelRef.current;
    if (!el) return;
    const { hasMore, isLoadingMore, onLoadMore } = listInfiniteLoad;
    const obs = new IntersectionObserver(
      (entries) => {
        const hit = entries.some((e) => e.isIntersecting);
        if (!hit) return;
        if (hasMore && !isLoadingMore) onLoadMore();
      },
      { root: null, rootMargin: "160px", threshold: 0 },
    );
    obs.observe(el);
    return () => obs.disconnect();
  }, [
    listInfiniteLoad?.hasMore,
    listInfiniteLoad?.isLoadingMore,
    listInfiniteLoad?.onLoadMore,
  ]);

  const getStage = (stageId: string) => {
    const s = stages.find((st) => st.id === stageId);
    return s ?? { color: "#6C63FF", name: stageId };
  };

  const allSelected =
    !!selectedIds &&
    deals.length > 0 &&
    deals.every((d) => selectedIds.has(d.id));
  const someSelected =
    !!selectedIds && deals.some((d) => selectedIds.has(d.id)) && !allSelected;

  return (
    <div className="w-full min-h-0">
      <div className="w-full overflow-x-auto scrollbar-themed rounded-[14px] border border-white bg-[rgba(244,246,255,0.4)] backdrop-blur-[15px] shadow-[0px_2px_15px_0px_rgba(0,0,0,0.1)]">
      <Table variant="transparent">
        <TableHeader className="!bg-white shadow-[0_1px_0_0_rgba(229,231,235,1)]">
          <TableRow className="bg-white hover:bg-white">
            <TableHead className={cn(stickyHeadClass, "w-[50px] min-w-[50px] px-0 h-12")}>
              <div 
                className="flex items-center justify-center h-full w-full cursor-pointer"
                onClick={(e) => {
                  e.stopPropagation();
                  onSelectAll?.(!allSelected);
                }}
              >
                <div onClick={(e) => e.stopPropagation()}>
                  <Checkbox
                    checked={
                      allSelected ? true : someSelected ? "indeterminate" : false
                    }
                    onCheckedChange={(v) => onSelectAll?.(!!v)}
                    aria-label={selectAllAriaLabel}
                  />
                </div>
              </div>
            </TableHead>
            <TableHead className={stickyHeadClass}>
              <button
                onClick={() => onSort("customerName")}
                className="flex items-center gap-1.5 hover:text-accent transition-colors group/btn"
              >
                Customer
                <div
                  className={cn(
                    "transition-all duration-200",
                    sortCol === "customerName"
                      ? "opacity-100 scale-110 text-accent"
                      : "opacity-0 group-hover/btn:opacity-50",
                  )}
                />
              </button>
            </TableHead>
            <TableHead className={cn(stickyHeadClass, "hidden lg:table-cell")}>
              <button
                type="button"
                onClick={() => onSort("companyName")}
                className="flex items-center gap-1.5 hover:text-accent transition-colors group/btn"
              >
                Company
                <div
                  className={cn(
                    "transition-all duration-200",
                    sortCol === "companyName"
                      ? "opacity-100 scale-110 text-accent"
                      : "opacity-0 group-hover/btn:opacity-50",
                  )}
                />
              </button>
            </TableHead>
            <TableHead className={cn(stickyHeadClass, "hidden sm:table-cell text-center")}>
              Status
            </TableHead>
            <TableHead className={cn(stickyHeadClass, "hidden lg:table-cell")}>
              Channel
            </TableHead>
            <TableHead className={cn(stickyHeadClass, "hidden lg:table-cell")}>
              <button
                type="button"
                onClick={() => onSort("createdDate")}
                className="flex items-center gap-1.5 hover:text-accent transition-colors group/btn whitespace-nowrap"
              >
                Created
                <div
                  className={cn(
                    "transition-all duration-200",
                    sortCol === "createdDate"
                      ? "opacity-100 scale-110 text-accent"
                      : "opacity-0 group-hover/btn:opacity-50",
                  )}
                />
              </button>
            </TableHead>
            <TableHead className={cn(stickyHeadClass, "hidden lg:table-cell")}>
              Team
            </TableHead>
            <TableHead className={cn(stickyHeadClass, "hidden lg:table-cell")}>
              Stage
            </TableHead>
            <TableHead className={cn(stickyHeadClass, "hidden xl:table-cell")}>
              Intent
            </TableHead>
            <TableHead className={cn(stickyHeadClass, "hidden xl:table-cell")}>
              Brand
            </TableHead>
            <TableHead className={cn(stickyHeadClass, "hidden xl:table-cell")}>
              Service
            </TableHead>
            <TableHead className={cn(stickyHeadClass, "hidden xl:table-cell")}>
              Owner
            </TableHead>
            <TableHead className={cn(stickyHeadClass, "text-right")}>
              Actions
            </TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {deals.length === 0 ? (
            <TableRow>
              <TableCell colSpan={12} className="h-60 text-center">
                <div className="flex flex-col items-center justify-center text-center">
                  <div className="size-16 rounded-full bg-bg flex items-center justify-center mb-4">
                    <Eye size={24} className="text-gray-300" />
                  </div>
                  <p className="text-[15px] font-bold text-gray-700 font-['Lexend']">
                    {emptyTitle}
                  </p>
                  <p className="text-[13px] text-gray-500 font-['Lexend_Deca'] mt-1">
                    {emptySubtitle}
                  </p>
                </div>
              </TableCell>
            </TableRow>
          ) : (
            deals.map((deal) => {
              const stage = getStage(deal.stage);
              const isSelected = selectedIds?.has(deal.id) ?? false;
              const serviceLabel =
                (typeof deal.service === "object" && deal.service != null
                  ? (deal.service as { name?: string }).name
                  : typeof deal.service === "string"
                    ? deal.service
                    : undefined) || deal.serviceName;
              const ownerLabel =
                deal.owner?.name?.trim() ||
                (typeof deal.createdBy === "string"
                  ? deal.createdBy.trim()
                  : "") ||
                (typeof deal.createdBy === "object" &&
                deal.createdBy !== null &&
                "name" in deal.createdBy &&
                typeof (deal.createdBy as { name?: unknown }).name === "string"
                  ? String((deal.createdBy as { name: string }).name).trim()
                  : "") ||
                null;
              return (
                <TableRow
                  key={deal.id as string}
                  onClick={() => onOpen(deal)}
                  className={cn(
                    "group transition-colors cursor-pointer",
                    isSelected && "bg-accent/5",
                  )}
                >
                  <TableCell
                    onClick={(e) => {
                      e.stopPropagation();
                      onSelectId?.(deal.id, !isSelected);
                    }}
                    className="px-0 cursor-pointer w-[50px] min-w-[50px]"
                  >
                    <div className="flex items-center justify-center h-full w-full" onClick={(e) => e.stopPropagation()}>
                      <Checkbox
                        checked={isSelected}
                        onCheckedChange={(v) => onSelectId?.(deal.id, !!v)}
                        aria-label={`Select ${deal.customerName}`}
                      />
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="flex items-center gap-3 min-w-0">
                      <div
                        className="h-9 w-9 rounded-xl flex items-center justify-center text-white text-[11px] font-black shrink-0 shadow-sm font-['Lexend_Deca'] border border-white/20"
                        style={{
                          backgroundColor: avatarColor(deal.customerName),
                        }}
                      >
                        {initials(deal.customerName)}
                      </div>
                      <div className="min-w-0">
                        <p className="text-[14px] font-bold text-text truncate font-['Lexend'] group-hover:text-accent transition-colors">
                          {deal.customerName || "Unnamed"}
                        </p>
                        {deal.companyName ? (
                          <p className="text-[11px] text-gray-500 truncate font-['Lexend_Deca'] mt-0.5 lg:hidden">
                            {deal.companyName}
                          </p>
                        ) : null}
                        <div className="flex items-center gap-2 mt-0.5">
                          <p className="text-[11.5px] text-gray-400 truncate font-['Lexend_Deca']">
                            {deal.email ||
                              deal.phone ||
                              deal.homePhone ||
                              "No contact info"}
                          </p>
                        </div>
                      </div>
                    </div>
                  </TableCell>
                  <TableCell className="hidden lg:table-cell">
                    <span className="text-[13px] text-gray-700 truncate font-['Lexend_Deca']">
                      {deal.companyName || "—"}
                    </span>
                  </TableCell>
                  <TableCell className="hidden sm:table-cell text-center">
                    {deal.leadStatus ? (
                      <span
                        className="inline-block text-[9px] leading-tight sm:text-[10px] font-black px-1.5 py-1 sm:px-2.5 sm:py-1 rounded-lg bg-accent/5 text-accent border border-accent/10 font-['Lexend_Deca'] uppercase truncate"
                        title={deal.leadStatus}
                      >
                        {deal.leadStatus}
                      </span>
                    ) : (
                      <span className="text-[12px] text-gray-300">—</span>
                    )}
                  </TableCell>
                  <TableCell className="hidden lg:table-cell">
                    {deal.leadChannel ? (
                      <span className="text-[12px] text-gray-700 truncate font-['Lexend_Deca']">
                        {typeof deal.leadChannel === "object"
                          ? (deal.leadChannel as { name?: string }).name
                          : deal.leadChannel}
                      </span>
                    ) : (
                      <span className="text-[12px] text-gray-300">—</span>
                    )}
                  </TableCell>
                  <TableCell className="hidden lg:table-cell">
                    <span className="text-[13px] text-gray-600 tabular-nums font-['Lexend_Deca']">
                      {formatCreatedDate(deal)}
                    </span>
                  </TableCell>
                  <TableCell className="hidden lg:table-cell">
                    {deal.team ? (
                      <span
                        className="inline-block truncate text-[10px] font-bold px-2.5 py-1 rounded-lg bg-green-50 text-green-600 border border-green-100 font-['Lexend_Deca']"
                        title={formatTeamLabelForUi(deal.team)}
                      >
                        {formatTeamLabelForUi(deal.team)}
                      </span>
                    ) : (
                      <span className="text-[12px] text-gray-300">—</span>
                    )}
                  </TableCell>
                  <TableCell className="hidden lg:table-cell">
                    <span
                      className="inline-block truncate text-[10px] font-black px-2.5 py-1 rounded-lg font-['Lexend_Deca'] tracking-wide border"
                      style={{
                        backgroundColor: `${stage.color}10`,
                        color: stage.color,
                        borderColor: `${stage.color}25`,
                      }}
                      title={stage.name}
                    >
                      {stage.name}
                    </span>
                  </TableCell>
                  <TableCell className="hidden xl:table-cell">
                    {deal.timelineIntent ? (
                      <span className="text-[12px] text-gray-700 truncate font-['Lexend_Deca']">
                        {typeof deal.timelineIntent === "object"
                          ? deal.timelineIntent?.name
                          : deal.timelineIntent}
                      </span>
                    ) : (
                      <span className="text-[12px] text-gray-300">—</span>
                    )}
                  </TableCell>
                  <TableCell className="hidden xl:table-cell">
                    {deal.brand ? (
                      <span
                        className="text-[13px] font-medium text-gray-600 font-['Lexend_Deca'] truncate block"
                        title={String(deal.brand)}
                      >
                        {deal.brand}
                      </span>
                    ) : (
                      <span className="text-gray-300">—</span>
                    )}
                  </TableCell>
                  <TableCell className="hidden xl:table-cell">
                    {serviceLabel ? (
                      <span
                        className="text-[13px] font-medium text-gray-600 font-['Lexend_Deca'] truncate block"
                        title={String(serviceLabel)}
                      >
                        {serviceLabel}
                      </span>
                    ) : (
                      <span className="text-gray-300">—</span>
                    )}
                  </TableCell>
                  <TableCell className="hidden xl:table-cell">
                    {ownerLabel ? (
                      <span
                        className="text-[13px] font-medium text-gray-600 font-['Lexend_Deca'] truncate block"
                        title={ownerLabel}
                      >
                        {ownerLabel}
                      </span>
                    ) : (
                      <span className="text-gray-300">—</span>
                    )}
                  </TableCell>
                  <TableCell
                    className="text-right"
                    onClick={(e) => e.stopPropagation()}
                  >
                    <DropdownMenu>
                      <DropdownMenuTrigger asChild>
                        <Button
                          variant="ghost"
                          size="icon"
                          className="h-8 w-8 rounded-xl hover:bg-accent/10 hover:text-accent transition-all duration-200"
                        >
                          <MoreHorizontal size={16} />
                        </Button>
                      </DropdownMenuTrigger>
                      <DropdownMenuContent align="end" className="w-40 rounded-xl shadow-premium border-border/40 p-1.5">
                        <Can action="read" subject={canSubject}>
                          <DropdownMenuItem
                            onClick={() => onOpen(deal)}
                            className="flex items-center gap-2.5 px-3 py-2 rounded-lg text-[13px] font-medium text-gray-600 hover:text-accent hover:bg-accent/5 focus:bg-accent/5 focus:text-accent transition-colors cursor-pointer"
                          >
                            <Eye size={14} className="text-gray-400" />
                            View details
                          </DropdownMenuItem>
                        </Can>
                        <Can action="update" subject={canSubject}>
                          <DropdownMenuItem
                            onClick={() => onEdit(deal)}
                            className="flex items-center gap-2.5 px-3 py-2 rounded-lg text-[13px] font-medium text-gray-600 hover:text-accent hover:bg-accent/5 focus:bg-accent/5 focus:text-accent transition-colors cursor-pointer"
                          >
                            <PencilLine size={14} className="text-gray-400" />
                            Edit lead
                          </DropdownMenuItem>
                        </Can>
                        <Can action="delete" subject={canSubject}>
                          <DropdownMenuItem
                            onClick={() => onDelete(deal.id as string)}
                            className="flex items-center gap-2.5 px-3 py-2 rounded-lg text-[13px] font-medium text-red-600 hover:text-red-700 hover:bg-red-50 focus:bg-red-50 focus:text-red-700 transition-colors cursor-pointer"
                          >
                            <Trash2 size={14} className="text-red-400" />
                            Delete
                          </DropdownMenuItem>
                        </Can>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </TableCell>
                </TableRow>
              );
            })
          )}
        </TableBody>
      </Table>
      </div>
      {listInfiniteLoad && deals.length > 0 ? (
        <div
          ref={loadMoreSentinelRef}
          className="flex min-h-14 items-center justify-center py-4"
          aria-hidden
        >
          {listInfiniteLoad.isLoadingMore ? (
            <Spinner className="size-6 text-accent" />
          ) : null}
        </div>
      ) : null}
    </div>
  );
}
