"use client";

import * as React from "react";
import { resolveCustomerTenant } from "@/app/customer/_lib/resolve-customer-tenant";
import Link from "next/link";
import { useParams } from "next/navigation";
import { RefreshCw, X } from "lucide-react";
import { toast } from "sonner";

import {
  CustomerFieldsButton,
  CustomerFieldsPanel,
} from "@/app/customer/_components/customer-fields-panel";
import { useCustomerTableColumnPrefs } from "@/app/customer/_lib/use-customer-table-column-prefs";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";

import { PortfolioAnalyticsFiltersDialog } from "./portfolio-analytics-filters-dialog";
import { PortfolioAnalyticsChartPanel } from "./portfolio-analytics-charts";
import { PortfolioAnalyticsHoldingsTable } from "./portfolio-analytics-holdings-table";
import { PortfolioAnalyticsReportTable } from "./portfolio-analytics-report-table";
import { usePortfolioAnalyticsViewState } from "./use-portfolio-analytics-view-state";
import { formatPlainAmount } from "@/lib/format/numbers";
import {
  PORTFOLIO_ANALYTICS_FIELDS_CATALOG,
  PORTFOLIO_ANALYTICS_LOCKED_KEYS,
  PORTFOLIO_ANALYTICS_TOTAL_COLUMN_KEYS_SET,
  PORTFOLIO_ANALYTICS_TOTALS_CATALOG,
  computePortfolioAnalyticsHoldingsTotals,
  type PortfolioAnalyticsHoldingsColumnKey,
} from "./portfolio-analytics-columns";

export function PortfolioAnalyticsView() {
  const params = useParams<{ tenant?: string }>();
  const tenant = typeof params?.tenant === "string" && params.tenant.trim() ? params.tenant.trim() : resolveCustomerTenant();
  const s = usePortfolioAnalyticsViewState(tenant);
  const [fieldsOpen, setFieldsOpen] = React.useState(false);

  // Columns stay locked/visible; prefs hook only backs the Fields panel shell.
  const {
    columnVisibility,
    columnOrder,
    hideAll,
    setColumnVisible,
    reorderShown,
  } = useCustomerTableColumnPrefs({
    catalog: PORTFOLIO_ANALYTICS_FIELDS_CATALOG,
    initialPrefs: null,
    lockedKeys: PORTFOLIO_ANALYTICS_LOCKED_KEYS,
    savePrefs: async () => {},
  });

  const {
    columnVisibility: totalColumnVisibility,
    columnOrder: totalColumnOrder,
    onColumnVisibilityChange: onTotalColumnVisibilityChange,
  } = useCustomerTableColumnPrefs({
    catalog: PORTFOLIO_ANALYTICS_TOTALS_CATALOG,
    initialPrefs: null,
    savePrefs: async () => {},
  });

  const holdingsTotals = React.useMemo(
    () => computePortfolioAnalyticsHoldingsTotals(s.tableRows),
    [s.tableRows],
  );

  const selectedTotalColumns = React.useMemo(() => {
    const totalsByKey: Record<string, number> = {
      purchaseValueRc: holdingsTotals.purchaseValueRc,
      value: holdingsTotals.value,
    };
    return totalColumnOrder
      .filter((key) => totalColumnVisibility[key] !== false)
      .map((key) => {
        const column = PORTFOLIO_ANALYTICS_FIELDS_CATALOG.find((entry) => entry.key === key);
        if (!column || !(key in totalsByKey)) return null;
        return {
          key: key as PortfolioAnalyticsHoldingsColumnKey,
          label: column.label,
          value: totalsByKey[key],
        };
      })
      .filter(
        (entry): entry is { key: PortfolioAnalyticsHoldingsColumnKey; label: string; value: number } =>
          Boolean(entry),
      );
  }, [holdingsTotals.purchaseValueRc, holdingsTotals.value, totalColumnOrder, totalColumnVisibility]);

  return (
    <div className="flex min-w-0 flex-col gap-4">
      <div className="mb-4 flex w-full min-w-0 flex-col gap-4 border-b pb-4 sm:flex-row sm:items-center">
        <div className="min-w-0 shrink-0">
          <h1 className="font-semibold text-2xl tracking-tight">Portfolio Analytics</h1>
          <p className="text-muted-foreground text-sm">
            Displaying {formatPlainAmount(s.filteredHoldings.length)} positions
            {s.hasActiveFilters ? " · filters applied" : ""}
            {s.isLoading || (s.tab === "report" && s.reportLoading) ? " · Loading…" : ""}
          </p>
          {s.loadErrorMessage ? <p className="text-destructive text-sm">{s.loadErrorMessage}</p> : null}
          {s.tab === "report" && s.reportErrorMessage ? (
            <p className="text-destructive text-sm">{s.reportErrorMessage}</p>
          ) : null}
        </div>

        <div className="flex w-full min-w-0 flex-wrap items-center justify-end gap-2 sm:ml-auto sm:w-auto">
          <PortfolioAnalyticsFiltersDialog
            filters={s.filters}
            defaultFilters={s.defaultFilters}
            options={s.filterOptionLists}
            onApply={s.applyFilters}
            toDateOnly={s.tab === "report"}
          />
          {s.tab === "graph" ? (
            <CustomerFieldsButton onClick={() => setFieldsOpen(true)} />
          ) : null}
          <Button
            variant="outline"
            size="icon-lg"
            className="h-9 w-9 shrink-0"
            aria-label="Refresh report"
            onClick={s.handleRefresh}
          >
            <RefreshCw className={cn("size-4", (s.isLoading || s.reportLoading) && "animate-spin")} />
          </Button>
          <Button variant="outline" size="icon-lg" className="h-9 w-9 shrink-0" asChild>
            <Link href={`/customer/${tenant}/reports`} aria-label="Close report">
              <X className="size-4" />
            </Link>
          </Button>
        </div>
      </div>

      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <div className="inline-flex items-center gap-1 rounded-lg border border-border/60 bg-muted/30 p-1">
          <Button
            variant="ghost"
            size="sm"
            className={cn(
              "h-8 rounded-md px-4 text-sm shadow-none",
              s.tab === "graph"
                ? "bg-background text-foreground shadow-sm"
                : "text-muted-foreground hover:bg-transparent hover:text-foreground",
            )}
            onClick={() => s.handleTabChange("graph")}
          >
            Graph
          </Button>
          <Button
            variant="ghost"
            size="sm"
            className={cn(
              "h-8 rounded-md px-4 text-sm shadow-none",
              s.tab === "report"
                ? "bg-background text-foreground shadow-sm"
                : "text-muted-foreground hover:bg-transparent hover:text-foreground",
            )}
            onClick={() => s.handleTabChange("report")}
          >
            Report
          </Button>
        </div>
        <div className="flex flex-wrap items-center gap-x-1 gap-y-1">
          <Button variant="ghost" size="sm" className="h-8 px-2.5 text-muted-foreground text-xs hover:text-foreground" asChild>
            <Link href={`/customer/${tenant}/reports/debt-intelligence-report`}>Debt Intelligence</Link>
          </Button>
          <span className="hidden text-border sm:inline">·</span>
          <Button variant="ghost" size="sm" className="h-8 px-2.5 text-muted-foreground text-xs hover:text-foreground" asChild>
            <Link href={`/customer/${tenant}/reports/cashflow`}>Cash Flows</Link>
          </Button>
          {["Return Analysis", "Recent Transactions", "Top 5 Holdings", "Liquidity", "Fees"].map((label) => (
            <React.Fragment key={label}>
              <span className="hidden text-border sm:inline">·</span>
              <Button
                variant="ghost"
                size="sm"
                className="h-8 px-2.5 text-muted-foreground/70 text-xs hover:text-foreground"
                onClick={() => toast.info(`${label} will open when connected to the legacy module`)}
              >
                {label}
              </Button>
            </React.Fragment>
          ))}
        </div>
      </div>

      {s.tab === "graph" ? (
        <>
          <PortfolioAnalyticsChartPanel
            isLoading={s.isLoading}
            chartData={s.chartData}
            chartSeriesConfig={s.chartSeriesConfig}
            visibleChartSeries={s.visibleChartSeries}
            apiSeries={s.apiSeries}
            filters={s.filters}
            filterOptionLists={s.filterOptionLists}
            focusedSeries={s.focusedSeries}
            onLegendClick={s.handleLegendClick}
            onClearFocus={() => s.setFocusedSeries(null)}
          />
          <PortfolioAnalyticsHoldingsTable
            isLoading={s.isLoading}
            filters={s.filters}
            tableRows={s.tableRows}
            pageRows={s.pageRows}
            sortKey={s.sortKey}
            sortOrder={s.sortOrder}
            onSort={s.handleSort}
            filterType={s.filterType}
            filterBank={s.filterBank}
            filterAssetType={s.filterAssetType}
            filterCurrency={s.filterCurrency}
            onFilterTypeChange={(v) => { s.setFilterType(v); s.setPageIndex(0); }}
            onFilterBankChange={(v) => { s.setFilterBank(v); s.setPageIndex(0); }}
            onFilterAssetTypeChange={(v) => { s.setFilterAssetType(v); s.setPageIndex(0); }}
            onFilterCurrencyChange={(v) => { s.setFilterCurrency(v); s.setPageIndex(0); }}
            pageIndex={s.pageIndex}
            pageSize={s.pageSize}
            pageCount={s.pageCount}
            start={s.start}
            end={s.end}
            onPageIndexChange={s.setPageIndex}
            onPageSizeChange={(size) => { s.setPageSize(size); s.setPageIndex(0); }}
            selectedTotalColumns={selectedTotalColumns}
          />
        </>
      ) : (
        <PortfolioAnalyticsReportTable
          reportLoading={s.reportLoading}
          reportGroups={s.reportGroups}
          currencyCode={s.currencyCode}
          reportTotal={s.reportTotal}
          reportTotalExcluding={s.reportTotalExcluding}
          asOfLabel={s.asOfLabel}
        />
      )}

      <CustomerFieldsPanel
        open={fieldsOpen}
        onOpenChange={setFieldsOpen}
        catalog={PORTFOLIO_ANALYTICS_FIELDS_CATALOG}
        visibility={columnVisibility as Record<string, boolean>}
        order={columnOrder}
        lockedKeys={PORTFOLIO_ANALYTICS_LOCKED_KEYS}
        title="Fields"
        description="Toggle totals for Purchase Value RC and Value. Column visibility is fixed for this report."
        onToggle={setColumnVisible}
        onReorder={reorderShown}
        onHideAll={hideAll}
        totalKeys={PORTFOLIO_ANALYTICS_TOTAL_COLUMN_KEYS_SET}
        totalVisibility={totalColumnVisibility as Record<string, boolean>}
        onTotalToggle={(key, visible) =>
          onTotalColumnVisibilityChange((prev) => ({ ...prev, [key]: visible }))
        }
      />
    </div>
  );
}
