"use client";

import * as React from "react";
import { format, parseISO } from "date-fns";
import { Download } from "lucide-react";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { cn } from "@/lib/utils";

import { ReportLoadingPanel } from "@/app/customer/[tenant]/reports/_shared/components/report-loading-panel";
import {
  ReportPageNavigation,
  ReportRecordsPerPage,
  ReportSortableHead,
  ReportTableHead,
} from "@/app/customer/[tenant]/reports/_shared/components/report-table-chrome";
import {
  type PortfolioAnalyticsFilters,
  type PortfolioAnalyticsRow,
  type PortfolioAnalyticsSortKey,
  type PortfolioAnalyticsSortOrder,
} from "./schema";
import { exportRowsCsv, formatAmount, portfolioAnalyticsCsvFilename } from "./utils";
import { formatPlainAmount } from "@/lib/format/numbers";
import {
  PORTFOLIO_ANALYTICS_HOLDINGS_COLUMN_KEYS,
  PORTFOLIO_ANALYTICS_PAGE_SIZE_OPTIONS,
  type PortfolioAnalyticsHoldingsColumnKey,
} from "./portfolio-analytics-columns";

export function PortfolioAnalyticsHoldingsTable({
  isLoading,
  filters,
  tableRows,
  pageRows,
  sortKey: _sortKey,
  sortOrder: _sortOrder,
  onSort,
  filterType,
  filterBank,
  filterAssetType,
  filterCurrency,
  onFilterTypeChange,
  onFilterBankChange,
  onFilterAssetTypeChange,
  onFilterCurrencyChange,
  pageIndex,
  pageSize,
  pageCount,
  start,
  end,
  onPageIndexChange,
  onPageSizeChange,
  selectedTotalColumns = [],
}: {
  isLoading: boolean;
  filters: PortfolioAnalyticsFilters;
  tableRows: PortfolioAnalyticsRow[];
  pageRows: PortfolioAnalyticsRow[];
  sortKey: PortfolioAnalyticsSortKey | null;
  sortOrder: PortfolioAnalyticsSortOrder;
  onSort: (key: PortfolioAnalyticsSortKey) => void;
  filterType: string;
  filterBank: string;
  filterAssetType: string;
  filterCurrency: string;
  onFilterTypeChange: (value: string) => void;
  onFilterBankChange: (value: string) => void;
  onFilterAssetTypeChange: (value: string) => void;
  onFilterCurrencyChange: (value: string) => void;
  pageIndex: number;
  pageSize: number;
  pageCount: number;
  start: number;
  end: number;
  onPageIndexChange: (index: number) => void;
  onPageSizeChange: (size: number) => void;
  selectedTotalColumns?: Array<{
    key: PortfolioAnalyticsHoldingsColumnKey;
    label: string;
    value: number;
  }>;
}) {
  const handleExport = () => {
    const csv = exportRowsCsv(tableRows);
    const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = portfolioAnalyticsCsvFilename();
    link.click();
    URL.revokeObjectURL(url);
    toast.success("CSV downloaded");
  };

  const firstTotalColumnIndex = PORTFOLIO_ANALYTICS_HOLDINGS_COLUMN_KEYS.findIndex((key) =>
    selectedTotalColumns.some((entry) => entry.key === key),
  );
  const showTotalsFooter =
    !isLoading && tableRows.length > 0 && selectedTotalColumns.length > 0 && firstTotalColumnIndex >= 0;

  return (
    <div className="flex min-w-0 flex-col gap-4">
      <div className="mb-0 flex w-full min-w-0 flex-col gap-4 sm:flex-row sm:items-center">
        <div className="shrink-0">
          <h2 className="font-semibold text-lg tracking-tight">Holdings</h2>
          <p className="text-muted-foreground text-sm">
            Displaying {start}-{end} of {formatPlainAmount(tableRows.length)} results.
            {filters.fromDate && filters.toDate
              ? ` · ${format(parseISO(filters.fromDate), "d MMM yyyy")} – ${format(parseISO(filters.toDate), "d MMM yyyy")}`
              : ""}
          </p>
        </div>
        <div className="flex w-full min-w-0 flex-wrap items-center justify-end gap-2 sm:ml-auto sm:w-auto">
          <ReportRecordsPerPage
            id="portfolio-analytics-rows-per-page"
            pageSize={pageSize}
            options={PORTFOLIO_ANALYTICS_PAGE_SIZE_OPTIONS}
            onPageSizeChange={onPageSizeChange}
          />
          <Button
            variant="outline"
            size="sm"
            className="h-9 gap-2"
            onClick={handleExport}
          >
            <Download className="size-3.5" />
            Download CSV
          </Button>
        </div>
      </div>

      <ReportLoadingPanel
        loading={isLoading}
        label="Loading holdings…"
        className={cn(isLoading && "pointer-events-none")}
      >
        <div className="overflow-x-auto rounded-lg border bg-card">
          <Table>
            <TableHeader>
              <TableRow className="bg-muted/20 hover:bg-muted/20">
                <ReportSortableHead label="Asset Class" onSort={() => onSort("assetClass")} />
                <ReportSortableHead label="Bank" onSort={() => onSort("bank")} />
                <ReportSortableHead label="Date" onSort={() => onSort("date")} />
                <ReportSortableHead label="Asset Type" onSort={() => onSort("assetType")} />
                <ReportSortableHead label="Currency" onSort={() => onSort("currency")} />
                <ReportTableHead className="text-muted-foreground">Geography</ReportTableHead>
                <ReportTableHead className="text-muted-foreground">Industry</ReportTableHead>
                <ReportTableHead className="text-muted-foreground">Sector</ReportTableHead>
                <ReportSortableHead
                  label="Purchase Value RC"
                  onSort={() => onSort("purchaseValueRc")}
                  align="right"
                />
                <ReportSortableHead label="Value" onSort={() => onSort("value")} align="right" />
              </TableRow>
              <TableRow className="bg-muted/10 hover:bg-muted/10">
                <TableHead className="px-2 py-2">
                  <Input
                    placeholder="Filter"
                    value={filterType}
                    onChange={(e) => onFilterTypeChange(e.target.value)}
                    className="h-8 min-w-28 text-xs"
                  />
                </TableHead>
                <TableHead className="px-2 py-2">
                  <Input
                    placeholder="Filter"
                    value={filterBank}
                    onChange={(e) => onFilterBankChange(e.target.value)}
                    className="h-8 min-w-28 text-xs"
                  />
                </TableHead>
                <TableHead className="px-2 py-2" />
                <TableHead className="px-2 py-2">
                  <Input
                    placeholder="Filter"
                    value={filterAssetType}
                    onChange={(e) => onFilterAssetTypeChange(e.target.value)}
                    className="h-8 min-w-28 text-xs"
                  />
                </TableHead>
                <TableHead className="px-2 py-2">
                  <Input
                    placeholder="Filter"
                    value={filterCurrency}
                    onChange={(e) => onFilterCurrencyChange(e.target.value)}
                    className="h-8 min-w-28 text-xs"
                  />
                </TableHead>
                <TableHead colSpan={5} className="px-2 py-2" />
              </TableRow>
            </TableHeader>
            <TableBody>
              {pageRows.length === 0 ? (
                !isLoading ? (
                  <TableRow>
                    <TableCell colSpan={10} className="h-24 text-center text-muted-foreground text-sm">
                      No holdings match the current filters
                    </TableCell>
                  </TableRow>
                ) : (
                  <TableRow>
                    <TableCell colSpan={10} className="h-24 text-center text-muted-foreground text-sm">
                      Loading...
                    </TableCell>
                  </TableRow>
                )
              ) : (
                pageRows.map((row, index) => (
                  <TableRow key={`${row.id}-${index}`} className={index % 2 === 0 ? "bg-muted/5" : undefined}>
                    <TableCell className="px-2 py-2 align-middle font-medium text-sm">{row.assetClass}</TableCell>
                    <TableCell className="px-2 py-2 align-middle text-muted-foreground text-sm">{row.bank}</TableCell>
                    <TableCell className="px-2 py-2 align-middle text-muted-foreground text-sm tabular-nums">
                      {row.date ? format(parseISO(row.date), "dd/MM/yyyy") : "—"}
                    </TableCell>
                    <TableCell className="max-w-[180px] truncate px-2 py-2 align-middle text-muted-foreground text-sm">
                      {row.assetType}
                    </TableCell>
                    <TableCell className="px-2 py-2 align-middle font-mono text-muted-foreground text-xs">{row.currency}</TableCell>
                    <TableCell className="px-2 py-2 align-middle text-muted-foreground text-sm">{row.country}</TableCell>
                    <TableCell className="px-2 py-2 align-middle text-muted-foreground text-sm">{row.industry}</TableCell>
                    <TableCell className="px-2 py-2 align-middle text-muted-foreground text-sm">{row.sector}</TableCell>
                    <TableCell className="px-2 py-2 align-middle text-right text-muted-foreground text-sm tabular-nums">
                      {formatAmount(row.purchaseValueRc)}
                    </TableCell>
                    <TableCell className="px-2 py-2 align-middle text-right font-medium text-sm tabular-nums">
                      {formatAmount(row.value)}
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
            {showTotalsFooter ? (
              <tfoot>
                <TableRow className="border-t-2 bg-muted/40 font-semibold hover:bg-muted/40">
                  {firstTotalColumnIndex > 0 ? (
                    <TableCell colSpan={firstTotalColumnIndex} className="px-2 py-2 text-right text-xs">
                      Total
                    </TableCell>
                  ) : null}
                  {PORTFOLIO_ANALYTICS_HOLDINGS_COLUMN_KEYS.slice(
                    Math.max(firstTotalColumnIndex, 0),
                  ).map((key) => {
                    const selectedTotal = selectedTotalColumns.find((entry) => entry.key === key);
                    return (
                      <TableCell
                        key={key}
                        className={cn(
                          "px-2 py-2 text-xs",
                          (key === "purchaseValueRc" || key === "value") && "text-right tabular-nums",
                        )}
                      >
                        {selectedTotal ? (
                          <div className="text-right">
                            <span className="block text-[11px] font-normal text-muted-foreground">
                              Total {selectedTotal.label}
                            </span>
                            <span className="font-semibold">{formatAmount(selectedTotal.value)}</span>
                          </div>
                        ) : null}
                      </TableCell>
                    );
                  })}
                </TableRow>
              </tfoot>
            ) : null}
          </Table>
        </div>
      </ReportLoadingPanel>

      {tableRows.length > 0 ? (
        <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
          <p className="text-muted-foreground text-sm">
            Page {pageCount === 0 ? 0 : pageIndex + 1} of {pageCount}
          </p>
          <ReportPageNavigation
            page={pageIndex + 1}
            pageCount={pageCount}
            onPageChange={(page) => onPageIndexChange(page - 1)}
            disabled={isLoading}
          />
        </div>
      ) : null}
    </div>
  );
}
