"use client";

import * as React from "react";
import { Landmark } from "lucide-react";

import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "@/components/ui/accordion";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { formatAmount } from "@/lib/format/numbers";
import { cn } from "@/lib/utils";

import { CurrencyBadge, currencyAccentClass } from "./report-view-primitives";

export type BankCurrencyGroup<Row> = { bank: string; rows: Row[] };

export type BankCurrencyColumn<Row> = {
  header: string;
  cell: (row: Row) => React.ReactNode;
  /** Extra classes on the body cell (e.g. numeric emphasis). */
  cellClassName?: string;
};

type BankCurrencyAccordionProps<Row extends { currency: string }> = {
  groups: BankCurrencyGroup<Row>[];
  defaultOpen: string[];
  /** Amount shown in each currency chip of the collapsed header. */
  chipAmount: (row: Row) => number;
  /** Right-aligned numeric columns after the leading Currency column. */
  columns: BankCurrencyColumn<Row>[];
};

const CHIP_LIMIT = 6;

/**
 * Per-bank accordion of currency rows for the cash balance report: a header with the bank name and
 * currency chips, and a table of one row per currency underneath.
 */
export function BankCurrencyAccordion<Row extends { currency: string }>({
  groups,
  defaultOpen,
  chipAmount,
  columns,
}: BankCurrencyAccordionProps<Row>) {
  return (
    <Accordion
      key={groups.map((group) => group.bank).join("|")}
      type="multiple"
      defaultValue={defaultOpen}
      className="gap-3"
    >
      {groups.map((group) => (
        <AccordionItem
          key={group.bank}
          value={group.bank}
          className="overflow-hidden rounded-lg border border-border/80 bg-card shadow-xs not-last:border-b-0"
        >
          <AccordionTrigger className="rounded-none border-0 px-4 py-3.5 hover:bg-muted/40 hover:no-underline data-[state=open]:border-b data-[state=open]:bg-muted/25">
            <div className="flex min-w-0 flex-1 flex-col gap-2.5 pr-3 lg:flex-row lg:items-center lg:justify-between">
              <div className="flex min-w-0 items-center gap-2.5">
                <div className="flex size-9 shrink-0 items-center justify-center rounded-lg border border-violet-700/15 bg-violet-700/[0.06] text-violet-700 dark:border-violet-300/20 dark:bg-violet-300/10 dark:text-violet-300">
                  <Landmark className="size-4" />
                </div>
                <div className="min-w-0 text-left">
                  <p className="truncate font-semibold text-sm leading-none">{group.bank}</p>
                  <p className="mt-1 text-muted-foreground text-xs">
                    {group.rows.length} {group.rows.length === 1 ? "currency" : "currencies"}
                  </p>
                </div>
              </div>
              <div className="flex max-w-full flex-wrap gap-1.5 lg:justify-end">
                {group.rows.slice(0, CHIP_LIMIT).map((row) => (
                  <span
                    key={`${group.bank}-chip-${row.currency}`}
                    className={cn(
                      "inline-flex items-center gap-1.5 rounded-md border px-2 py-1 text-xs",
                      currencyAccentClass(row.currency),
                    )}
                  >
                    <span className="font-mono font-medium">{row.currency}</span>
                    <span className="tabular-nums text-foreground">{formatAmount(chipAmount(row))}</span>
                  </span>
                ))}
                {group.rows.length > CHIP_LIMIT ? (
                  <span className="inline-flex items-center rounded-md border border-border/80 bg-muted/50 px-2 py-1 text-muted-foreground text-xs">
                    +{group.rows.length - CHIP_LIMIT} more
                  </span>
                ) : null}
              </div>
            </div>
          </AccordionTrigger>
          <AccordionContent className="pb-0">
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow className="hover:bg-transparent">
                    <TableHead className="h-9 bg-muted/20 px-3 text-sm">Currency</TableHead>
                    {columns.map((column) => (
                      <TableHead
                        key={column.header}
                        className="h-9 bg-muted/20 px-3 text-right text-sm"
                      >
                        {column.header}
                      </TableHead>
                    ))}
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {group.rows.map((row) => (
                    <TableRow key={`${group.bank}-${row.currency}`} className="hover:bg-primary/[0.03]">
                      <TableCell className="px-3 py-2">
                        <CurrencyBadge currency={row.currency} />
                      </TableCell>
                      {columns.map((column) => (
                        <TableCell
                          key={column.header}
                          className={cn("px-3 py-2 text-right text-sm", column.cellClassName)}
                        >
                          {column.cell(row)}
                        </TableCell>
                      ))}
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          </AccordionContent>
        </AccordionItem>
      ))}
    </Accordion>
  );
}
