"use client";

import * as React from "react";
import Link from "next/link";
import { Inbox, Search, Calendar, ChevronLeft, ChevronRight, User } from "lucide-react";
import { format } from "date-fns";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Loading } from "@/components/ui/loading";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { cn } from "@/lib/utils";
import type { BdrMetricsLeadRow } from "@/api/rtk/bdr-metrics-api";

const LEADS_PAGE_SIZE = 15;

const headClass =
  "h-11 px-4 py-0 text-[10px] font-bold uppercase tracking-wider text-gray-500 bg-gray-50/50";
const cellClass = "px-4 py-3 align-middle text-[12px] font-['Lexend_Deca']";

function formatLeadDateTime(iso: string): string {
  const d = new Date(iso);
  if (Number.isNaN(d.getTime())) return "—";
  return format(d, "MMM d, yyyy");
}

function getStageBadgeClass(stage: string): string {
  const s = (stage || "").toLowerCase();
  if (s.includes("new") || s.includes("assigned")) {
    return "bg-indigo-50 text-indigo-700 border-indigo-100/80";
  }
  if (s.includes("sql") || s.includes("qualify") || s.includes("qualified")) {
    return "bg-purple-50 text-purple-700 border-purple-100/80";
  }
  if (s.includes("meet") || s.includes("book") || s.includes("sched")) {
    return "bg-emerald-50 text-emerald-700 border-emerald-100/80";
  }
  return "bg-gray-50 text-gray-700 border-gray-100/80";
}

function filterLeads(leads: BdrMetricsLeadRow[], query: string): BdrMetricsLeadRow[] {
  const q = query.trim().toLowerCase();
  if (!q) return leads;
  return leads.filter((row) => {
    const haystack = [
      row.customerName,
      row.bdrAssigneeName ?? "",
      row.stageLabel,
      formatLeadDateTime(row.assignedAt),
      formatLeadDateTime(row.createdAt),
      formatLeadDateTime(row.updatedAt),
    ]
      .filter(Boolean)
      .join(" ")
      .toLowerCase();
    return haystack.includes(q);
  });
}

export type BdrMetricsLeadsPanelProps = {
  leads: BdrMetricsLeadRow[];
  bucketLabel: string;
  loading: boolean;
  search: string;
  onSearchChange: (value: string) => void;
  page: number;
  onPageChange: (page: number) => void;
  pageSize?: number;
};

export function BdrMetricsLeadsPanel({
  leads,
  bucketLabel,
  loading,
  search,
  onSearchChange,
  page,
  onPageChange,
  pageSize = LEADS_PAGE_SIZE,
}: BdrMetricsLeadsPanelProps) {
  const filtered = React.useMemo(
    () => filterLeads(leads, search),
    [leads, search],
  );

  const totalPages = Math.max(1, Math.ceil(filtered.length / pageSize));
  const safePage = Math.min(Math.max(1, page), totalPages);

  React.useEffect(() => {
    if (page !== safePage) onPageChange(safePage);
  }, [page, safePage, onPageChange]);

  const pageLeads = React.useMemo(() => {
    const start = (safePage - 1) * pageSize;
    return filtered.slice(start, start + pageSize);
  }, [filtered, safePage, pageSize]);

  const rangeStart = filtered.length === 0 ? 0 : (safePage - 1) * pageSize + 1;
  const rangeEnd = Math.min(safePage * pageSize, filtered.length);

  return (
    <div className="flex min-h-0 flex-1 flex-col">
      {/* Top Filter and Search Bar Row */}
      <div className="flex shrink-0 flex-col gap-3 border-b border-black/[0.05] bg-white/20 px-5 py-3 sm:flex-row sm:items-center sm:justify-between">
        <label className="relative block min-w-0 flex-1 sm:max-w-xs">
          <Search
            className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-gray-400"
            aria-hidden
          />
          <Input
            type="search"
            value={search}
            onChange={(e) => onSearchChange(e.target.value)}
            placeholder="Search lead title, assignee, stage, dates…"
            aria-label={`Search ${bucketLabel} leads`}
            className="h-9 rounded-xl border-white/60 bg-white/80 pl-9 font-['Lexend_Deca'] text-[12px] focus:border-indigo-300 focus:ring-indigo-200/50"
          />
        </label>
        {!loading && filtered.length > 0 && (
          <span className="shrink-0 rounded-full bg-gray-100/80 px-3 py-1 font-['Lexend_Deca'] text-[11px] font-bold tabular-nums text-gray-600 border border-black/[0.03]">
            {filtered.length} lead{filtered.length === 1 ? "" : "s"}
            {search.trim() ? ` · filtered from ${leads.length}` : ""}
          </span>
        )}
      </div>

      {/* Main Table Area */}
      <div className="min-h-0 flex-1 overflow-y-auto px-5 py-4 scrollbar-themed">
        {loading ? (
          <div className="flex items-center justify-center py-20">
            <Loading variant="spinner" message="Loading leads…" />
          </div>
        ) : leads.length === 0 ? (
          <EmptyBucketState bucketLabel={bucketLabel} variant="no_data" />
        ) : filtered.length === 0 ? (
          <EmptyBucketState
            bucketLabel={bucketLabel}
            variant="no_match"
            search={search}
          />
        ) : (
          <div className="overflow-hidden rounded-2xl border border-white/70 bg-white/60">
            <Table variant="transparent" className="table-fixed min-w-[780px]">
              <colgroup>
                <col className="w-[24%]" />
                <col className="w-[18%]" />
                <col className="w-[18%]" />
                <col className="w-[14%]" />
                <col className="w-[13%]" />
                <col className="w-[13%]" />
              </colgroup>
              <TableHeader>
                <TableRow className="border-b border-gray-200/80 hover:bg-transparent">
                  <TableHead className={cn(headClass, "text-left rounded-tl-2xl")}>
                    Lead Title
                  </TableHead>
                  <TableHead className={cn(headClass, "text-left")}>
                    Assignee
                  </TableHead>
                  <TableHead className={cn(headClass, "text-left")}>
                    Stage
                  </TableHead>
                  <TableHead className={cn(headClass, "text-right")}>
                    Assigned
                  </TableHead>
                  <TableHead className={cn(headClass, "text-right")}>
                    Created
                  </TableHead>
                  <TableHead className={cn(headClass, "text-right rounded-tr-2xl")}>
                    Updated
                  </TableHead>
                </TableRow>
              </TableHeader>
              <TableBody className="divide-y divide-gray-100/80">
                {pageLeads.map((row) => (
                  <TableRow
                    key={row.id}
                    className="group cursor-default hover:bg-indigo-50/20 transition-colors duration-200"
                  >
                    <TableCell className={cn(cellClass, "max-w-0")}>
                      <div className="flex items-center gap-2">
                        <span className="flex size-7 shrink-0 items-center justify-center rounded-lg bg-gray-100 text-gray-500 group-hover:bg-indigo-50 group-hover:text-indigo-600 transition-colors duration-200">
                          <User className="size-3.5" />
                        </span>
                        <Link
                          href={`/leads/${row.id}`}
                          className="block truncate font-bold text-indigo-600 hover:underline"
                          title={row.customerName ?? "Unnamed lead"}
                        >
                          {row.customerName ?? "Unnamed lead"}
                        </Link>
                      </div>
                    </TableCell>
                    <TableCell className={cn(cellClass, "max-w-0")}>
                      <span
                        className="block truncate font-semibold text-gray-800"
                        title={row.bdrAssigneeName ?? undefined}
                      >
                        {row.bdrAssigneeName ?? "—"}
                      </span>
                    </TableCell>
                    <TableCell className={cn(cellClass, "max-w-0")}>
                      <span
                        className={cn(
                          "inline-block max-w-full truncate rounded-lg border px-2 py-0.5 font-bold text-[11px]",
                          getStageBadgeClass(row.stageLabel)
                        )}
                        title={row.stageLabel}
                      >
                        {row.stageLabel}
                      </span>
                    </TableCell>
                    <TableCell
                      className={cn(
                        cellClass,
                        "text-right tabular-nums text-gray-600 whitespace-nowrap",
                      )}
                    >
                      {formatLeadDateTime(row.assignedAt)}
                    </TableCell>
                    <TableCell
                      className={cn(
                        cellClass,
                        "text-right tabular-nums text-gray-600 whitespace-nowrap",
                      )}
                    >
                      {formatLeadDateTime(row.createdAt)}
                    </TableCell>
                    <TableCell
                      className={cn(
                        cellClass,
                        "text-right tabular-nums text-gray-600 whitespace-nowrap",
                      )}
                    >
                      {formatLeadDateTime(row.updatedAt)}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
        )}
      </div>

      {/* Pagination Footer */}
      {!loading && filtered.length > 0 && (
        <div className="flex shrink-0 flex-col gap-3 border-t border-black/[0.05] bg-white/10 px-5 py-3 sm:flex-row sm:items-center sm:justify-between">
          <p className="font-['Lexend_Deca'] text-[11px] font-semibold tabular-nums text-gray-500">
            Showing <span className="font-bold text-gray-700">{rangeStart}</span>–<span className="font-bold text-gray-700">{rangeEnd}</span> of <span className="font-bold text-gray-700">{filtered.length}</span> leads
          </p>
          <div className="flex items-center gap-1.5">
            <Button
              type="button"
              variant="outline"
              size="sm"
              className="h-8 rounded-xl border-white/60 bg-white/70 px-2.5 hover:bg-white transition-all"
              disabled={safePage <= 1}
              onClick={() => onPageChange(safePage - 1)}
            >
              <ChevronLeft className="size-4" />
            </Button>
            <span className="min-w-[6.5rem] text-center font-['Lexend_Deca'] text-[11px] font-bold tabular-nums text-[#1d1d39]">
              Page {safePage} of {totalPages}
            </span>
            <Button
              type="button"
              variant="outline"
              size="sm"
              className="h-8 rounded-xl border-white/60 bg-white/70 px-2.5 hover:bg-white transition-all"
              disabled={safePage >= totalPages}
              onClick={() => onPageChange(safePage + 1)}
            >
              <ChevronRight className="size-4" />
            </Button>
          </div>
        </div>
      )}
    </div>
  );
}

function EmptyBucketState({
  bucketLabel,
  variant,
  search,
}: {
  bucketLabel: string;
  variant: "no_data" | "no_match";
  search?: string;
}) {
  return (
    <div className="flex flex-col items-center justify-center gap-3 rounded-2xl border border-dashed border-gray-200/80 bg-white/40 px-6 py-12 text-center">
      <span className="flex size-11 items-center justify-center rounded-2xl bg-indigo-50 text-indigo-500 border border-indigo-100">
        <Inbox className="size-5" aria-hidden />
      </span>
      <div>
        <p className="font-['Lexend'] text-[14px] font-bold text-[#1d1d39]">
          {variant === "no_match"
            ? `No matches in ${bucketLabel}`
            : `No leads in ${bucketLabel}`}
        </p>
        <p className="max-w-xs mt-1.5 font-['Lexend_Deca'] text-[11px] leading-relaxed text-gray-500">
          {variant === "no_match" ? (
            <>
              Nothing matches &ldquo;<span className="font-semibold text-gray-700">{search?.trim()}</span>&rdquo;. Try another term or
              clear the search.
            </>
          ) : (
            <>
              Try widening the date range, choosing another team or BDR, or pick a
              different bucket above.
            </>
          )}
        </p>
      </div>
    </div>
  );
}
