"use client";

import { cn } from "@/lib/utils";

import { AssetAllocationMiniPie } from "./asset-allocation-mini-pie";
import {
  type AllocationMatrix,
  buildPieSlicesAllBanks,
  buildPieSlicesForColumn,
  formatAllocationAmount,
  formatAllocationPct,
} from "./utils";

function amountClass(value: number, highlight?: boolean) {
  if (value < 0) {
    return highlight
      ? "bg-muted/40 font-semibold text-rose-600 dark:text-rose-400"
      : "font-medium text-rose-600 dark:text-rose-400";
  }
  if (value === 0) {
    return "text-muted-foreground/25";
  }
  return highlight ? "bg-muted/40 font-semibold" : "text-foreground";
}

function DataCell({
  value,
  pctScope,
  pctOverall,
  highlight,
}: {
  value: number;
  pctScope: number;
  pctOverall: number;
  highlight?: boolean;
}) {
  const empty = value === 0;
  return (
    <>
      <td
        className={cn(
          "px-3 py-2 text-right text-xs tabular-nums whitespace-nowrap",
          amountClass(value, highlight),
        )}
      >
        {empty ? "—" : formatAllocationAmount(value)}
      </td>
      <td
        className={cn(
          "px-3 py-2 text-right text-xs tabular-nums whitespace-nowrap",
          highlight ? "bg-muted/40 font-medium" : empty ? "text-muted-foreground/25" : "text-muted-foreground",
          pctScope < 0 && !empty && "text-rose-600 dark:text-rose-400",
        )}
      >
        {empty ? "—" : formatAllocationPct(pctScope)}
      </td>
      <td
        className={cn(
          "px-3 py-2 text-right text-xs tabular-nums whitespace-nowrap",
          highlight ? "bg-muted/40 font-medium" : empty ? "text-muted-foreground/25" : "text-muted-foreground",
          pctOverall < 0 && !empty && "text-rose-600 dark:text-rose-400",
        )}
      >
        {empty ? "—" : formatAllocationPct(pctOverall)}
      </td>
    </>
  );
}

export function AssetAllocationMatrix({
  matrix,
  rowLabel,
  totalsColumnLabel = "All Banks",
}: {
  matrix: AllocationMatrix;
  rowLabel: string;
  /** Yii1: "All Banks" (by class) / "All Asset Class" (by bank). */
  totalsColumnLabel?: string;
}) {
  const allBankSlices = buildPieSlicesAllBanks(matrix);

  if (matrix.columns.length === 0) {
    return (
      <div className="overflow-hidden rounded-xl border border-dashed border-border/80 bg-card py-20 text-center shadow-sm">
        <p className="font-medium text-muted-foreground text-sm">No banks selected</p>
        <p className="mt-1 text-muted-foreground text-xs">
          Open filters, choose at least one bank, then click Generate Report.
        </p>
      </div>
    );
  }

  return (
    <div className="overflow-hidden rounded-xl border border-border/80 bg-card shadow-sm">
      <div className="overflow-x-auto">
        <table className="w-max min-w-full border-collapse text-xs">
          <thead className="bg-background shadow-sm">
            <tr className="hover:bg-transparent">
              <th
                rowSpan={2}
                className="sticky left-0 z-40 min-w-[160px] border-b bg-muted/50 px-3 py-2 text-left font-semibold text-xs"
              >
                {rowLabel}
              </th>
              {matrix.columns.map((col) => (
                <th
                  key={col.id}
                  colSpan={3}
                  className="border-b bg-muted/50 px-3 py-2 text-center font-semibold text-xs"
                >
                  {col.label}
                </th>
              ))}
              <th
                colSpan={2}
                className="border-b bg-muted/50 px-3 py-2 text-center font-semibold text-xs"
              >
                {totalsColumnLabel}
              </th>
            </tr>
            <tr className="bg-muted/30 hover:bg-muted/30">
              {matrix.columns.map((col) => (
                <th
                  key={`${col.id}-sub`}
                  colSpan={3}
                  className="border-b bg-muted/30"
                >
                  <div className="grid grid-cols-3 text-[11px] font-medium text-muted-foreground">
                    <span className="px-2 py-1.5 text-right">{matrix.valueLabel}</span>
                    <span className="px-2 py-1.5 text-right">{matrix.scopeLabel}</span>
                    <span className="px-2 py-1.5 text-right">% Overall</span>
                  </div>
                </th>
              ))}
              <th
                colSpan={2}
                className="border-b bg-muted/30"
              >
                <div className="grid grid-cols-2 text-[11px] font-medium text-muted-foreground">
                  <span className="px-2 py-1.5 text-right">Grand Total</span>
                  <span className="px-2 py-1.5 text-right">% Overall</span>
                </div>
              </th>
            </tr>
            <tr className="bg-muted/20">
              <th className="sticky left-0 z-40 border-b bg-muted/30 px-3 py-1" />
              {matrix.columns.map((col) => (
                <td
                  key={`${col.id}-chart`}
                  colSpan={3}
                  className="border-b align-top"
                >
                  <AssetAllocationMiniPie slices={buildPieSlicesForColumn(matrix, col.id)} compact />
                </td>
              ))}
              <td colSpan={2} className="border-b align-top">
                <AssetAllocationMiniPie slices={allBankSlices} />
              </td>
            </tr>
          </thead>

          <tbody>
            {matrix.rows.map((row) => (
              <tr key={row.key}>
                <th
                  className="sticky left-0 z-20 min-w-[160px] border-b bg-background px-3 py-2 text-left font-medium text-xs"
                >
                  <span className="flex items-center gap-2">
                    <span
                      className="size-2 shrink-0 rounded-full"
                      style={{ backgroundColor: row.color }}
                    />
                    {row.label}
                  </span>
                </th>
                {matrix.columns.map((col) => {
                  const cell = row.cells[col.id] ?? { valueUsd: 0, pctOfScope: 0, pctOverall: 0 };
                  return (
                    <DataCell
                      key={`${row.key}-${col.id}`}
                      value={cell.valueUsd}
                      pctScope={cell.pctOfScope}
                      pctOverall={cell.pctOverall}
                    />
                  );
                })}
                <td
                  className={cn(
                    "px-3 py-2 text-right font-semibold text-xs tabular-nums whitespace-nowrap",
                    row.totalValue < 0 && "text-rose-600 dark:text-rose-400",
                  )}
                >
                  {row.totalValue === 0 ? "—" : formatAllocationAmount(row.totalValue)}
                </td>
                <td
                  className={cn(
                    "px-3 py-2 text-right font-medium text-muted-foreground text-xs tabular-nums whitespace-nowrap",
                    row.totalPctOverall < 0 && "text-rose-600 dark:text-rose-400",
                  )}
                >
                  {row.totalValue === 0 ? "—" : formatAllocationPct(row.totalPctOverall)}
                </td>
              </tr>
            ))}
          </tbody>

          <tfoot>
            <tr className="border-t-2 bg-muted/40 font-semibold">
              <th className="sticky left-0 z-30 bg-muted/40 px-3 py-2 text-left text-xs">
                Total
              </th>
              {matrix.columns.map((col) => {
                const cell = matrix.columnTotals[col.id] ?? {
                  valueUsd: 0,
                  pctOfScope: 0,
                  pctOverall: 0,
                };
                return (
                  <DataCell
                    key={`total-${col.id}`}
                    value={cell.valueUsd}
                    pctScope={cell.pctOfScope}
                    pctOverall={cell.pctOverall}
                    highlight
                  />
                );
              })}
              <td
                className={cn(
                  "bg-muted/40 px-3 py-2 text-right font-semibold text-xs tabular-nums whitespace-nowrap",
                  matrix.grandTotal < 0
                    ? "text-rose-600 dark:text-rose-400"
                    : "text-emerald-700 dark:text-emerald-400",
                )}
              >
                {formatAllocationAmount(matrix.grandTotal)}
              </td>
              <td className="bg-muted/40 px-3 py-2 text-right font-semibold text-xs text-emerald-700 tabular-nums whitespace-nowrap dark:text-emerald-400">
                {formatAllocationPct(matrix.grandPctOverall)}
              </td>
            </tr>
          </tfoot>
        </table>
      </div>
    </div>
  );
}
