import { useMemo, useState } from "react";
import { formatNumber } from "@/lib/report-utils";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";

export interface BankBalanceItem {
  bank_id: string;
  bank_name: string;
  code: string | null;
}

export interface BankBalanceRow {
  /** Item field holding this row's amount, e.g. "fixed_balance". */
  field: string;
  /** Appended to the bank name, e.g. "(FD)". */
  suffix?: string;
  /** Row tint; each balance kind reads differently at a glance. */
  tone?: "fixed" | "call" | "leverage";
}

interface BankBalanceTableProps {
  items: BankBalanceItem[] | undefined;
  /** One row per balance kind, rendered per bank in this order. */
  rows: readonly BankBalanceRow[];
  highlighted: string | null;
  onHighlight: (currency: string | null) => void;
}

interface RenderedRow {
  key: string;
  label: string;
  tone?: BankBalanceRow["tone"];
  values: Record<string, number>;
}

const PAGE_SIZES = [10, 20, 30, "All"] as const;

const TONE_CLASSES: Record<NonNullable<BankBalanceRow["tone"]>, string> = {
  fixed: "bg-green-50 hover:bg-green-100/50",
  call: "bg-blue-50 hover:bg-blue-100/50",
  leverage: "bg-red-50 hover:bg-red-100/50",
};

function toNumber(value: unknown): number {
  if (typeof value === "number") return Number.isFinite(value) ? value : 0;
  if (typeof value !== "string" || value === "") return 0;
  return parseFloat(value.replace(/,/g, "")) || 0;
}

/**
 * Bank × currency balance grid shared by the Cash Details and Cash Balance
 * reports. Each bank contributes one row per configured balance kind, and rows
 * that are zero across every currency are dropped.
 */
export function BankBalanceTable({
  items,
  rows,
  highlighted,
  onHighlight,
}: BankBalanceTableProps) {
  const [pageSize, setPageSize] = useState<number>(10);
  const [currentPage, setCurrentPage] = useState<number>(1);

  const { tableRows, currencies } = useMemo(() => {
    if (!items?.length) return { tableRows: [] as RenderedRow[], currencies: [] as string[] };

    const currencies = Array.from(
      new Set(items.map((i) => i.code).filter((c): c is string => Boolean(c)))
    ).sort();

    // Banks are keyed by id, not name: two banks can share a display name.
    const bankNames = new Map<string, string>();
    const amounts = new Map<string, number>();
    for (const item of items) {
      bankNames.set(item.bank_id, item.bank_name);
      for (const { field } of rows) {
        const amount = (item as unknown as Record<string, unknown>)[field];
        amounts.set(`${item.bank_id}|${item.code}|${field}`, toNumber(amount));
      }
    }

    const tableRows: RenderedRow[] = [];
    for (const [bankId, bankName] of bankNames) {
      for (const { field, suffix, tone } of rows) {
        const values: Record<string, number> = {};
        let total = 0;
        for (const currency of currencies) {
          const value = amounts.get(`${bankId}|${currency}|${field}`) ?? 0;
          values[currency] = value;
          total += value;
        }
        if (total === 0) continue;
        tableRows.push({
          key: `${bankId}-${field}`,
          label: suffix ? `${bankName} ${suffix}` : bankName,
          tone,
          values,
        });
      }
    }

    return { tableRows, currencies };
  }, [items, rows]);

  const rowCount = tableRows.length;
  const totalPages = pageSize === Infinity ? 1 : Math.max(1, Math.ceil(rowCount / pageSize));
  const page = Math.min(currentPage, totalPages);
  const firstIndex = pageSize === Infinity ? 0 : (page - 1) * pageSize;
  const lastIndex = pageSize === Infinity ? rowCount : Math.min(firstIndex + pageSize, rowCount);
  const paginatedRows = tableRows.slice(firstIndex, lastIndex);

  return (
    <div className="rounded-lg border border-white/70 bg-white/95 p-4 shadow-xl ring-1 ring-black/5 md:p-6">
      <div className="mb-4 flex flex-col items-end gap-3 sm:flex-row sm:justify-between">
        <div />
        <div className="flex flex-col items-end gap-3 sm:flex-row sm:items-center">
          <div className="flex items-center gap-2 text-sm text-muted-foreground">
            <span>Show</span>
            <Select
              value={pageSize === Infinity ? "All" : String(pageSize)}
              onValueChange={(v) => {
                setPageSize(v === "All" ? Infinity : Number(v));
                setCurrentPage(1);
              }}
            >
              <SelectTrigger size="sm" className="w-[4.75rem]" aria-label="Rows per page">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {PAGE_SIZES.map((size) => (
                  <SelectItem key={size} value={String(size)}>
                    {size}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <span>entries</span>
          </div>

          <div className="flex items-center gap-1">
            <button
              onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
              disabled={page === 1}
              className={`px-3 py-1.5 text-sm rounded-lg border ${page === 1 ? "border-border bg-muted text-muted-foreground cursor-not-allowed" : "border-border-strong bg-card text-foreground hover:bg-muted"}`}
            >
              Previous
            </button>
            <span className="px-3 py-1.5 text-sm text-foreground">
              Page {page} of {totalPages}
            </span>
            <button
              onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
              disabled={page === totalPages}
              className={`px-3 py-1.5 text-sm rounded-lg border ${page === totalPages ? "border-border bg-muted text-muted-foreground cursor-not-allowed" : "border-border-strong bg-card text-foreground hover:bg-muted"}`}
            >
              Next
            </button>
          </div>
        </div>
      </div>

      <div className="overflow-x-auto">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b-2 border-border bg-muted">
              <th className="px-4 py-3 text-left font-semibold text-foreground sticky left-0 bg-muted z-10 min-w-[200px]">
                Bank Name
              </th>
              {currencies.map((currency) => (
                <th
                  key={currency}
                  onClick={() => onHighlight(highlighted === currency ? null : currency)}
                  className={`px-4 py-3 text-right font-semibold cursor-pointer transition-all duration-300 whitespace-nowrap ${
                    highlighted === currency
                      ? "bg-primary/20 text-primary border-b-2 border-primary"
                      : "text-foreground hover:bg-primary/5"
                  }`}
                >
                  {currency}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {rowCount === 0 ? (
              <tr>
                <td
                  colSpan={currencies.length + 1}
                  className="px-4 py-8 text-center text-muted-foreground"
                >
                  No data available
                </td>
              </tr>
            ) : (
              paginatedRows.map((row) => (
                <tr
                  key={row.key}
                  className={`border-b border-border transition-colors ${row.tone ? TONE_CLASSES[row.tone] : "hover:bg-muted/50"}`}
                >
                  <td className="px-4 py-3 font-medium text-foreground sticky left-0 z-10 bg-inherit min-w-[200px]">
                    {row.label}
                  </td>
                  {currencies.map((currency) => {
                    const value = row.values[currency] || 0;
                    return (
                      <td
                        key={currency}
                        className={`px-4 py-3 text-right font-medium transition-all duration-300 whitespace-nowrap ${
                          highlighted === currency
                            ? "bg-primary/10 text-primary font-semibold"
                            : "text-foreground"
                        }`}
                      >
                        {value !== 0 ? formatNumber(value) : ".00"}
                      </td>
                    );
                  })}
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

      <div className="mt-4 text-center text-xs text-muted-foreground">
        Showing {rowCount === 0 ? 0 : firstIndex + 1} to {lastIndex} of {rowCount} entries
      </div>
    </div>
  );
}
