"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 {
  Activity,
  Download,
  LineChart,
  PiggyBank,
  RefreshCw,
  Scale,
  TrendingUp,
  Wallet,
  X,
} from "lucide-react";
import { CartesianGrid, Line, LineChart as RechartsLineChart, XAxis, YAxis } from "recharts";
import { toast } from "sonner";

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import {
  ChartContainer,
  ChartLegend,
  ChartLegendContent,
  ChartTooltip,
  ChartTooltipContent,
  type ChartConfig,
} from "@/components/ui/chart";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
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 { useAssetAllocationSummary } from "../../_lib/use-asset-allocation-summary";
import { usePerformanceSummaryReport } from "../../_lib/use-performance-summary-report";
import { usePerformanceSummaryWidget } from "../../_lib/use-performance-summary-widget";
import { AssetAllocationSummaryCard } from "./asset-allocation-summary-card";
import { useImpersonationScopeRefresh } from "@/app/customer/_lib/admin/use-impersonation-scope-refresh";
import {
  PERFORMANCE_SERIES_COLORS,
  buildPerformanceChartData,
  buildPerformanceLedgerRows,
  formatAmountField,
  formatReportValue,
} from "./utils";

function humanizeKey(key: string) {
  return key.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
}

function KpiCard({
  label,
  value,
  icon,
  hint,
}: {
  label: string;
  value: string;
  icon: React.ReactNode;
  hint?: string;
}) {
  return (
    <Card className="relative gap-0 overflow-hidden border-border/80 bg-card py-0 shadow-sm transition-shadow hover:shadow-md">
      <CardContent className="flex items-start justify-between gap-3 p-4 sm:p-5">
        <div className="min-w-0">
          <p className="font-medium text-[11px] text-muted-foreground uppercase tracking-[0.14em]">{label}</p>
          <p className="mt-2 truncate font-semibold text-xl tabular-nums tracking-tight leading-none sm:text-[1.35rem]">
            {value}
          </p>
          {hint ? <p className="mt-2 text-muted-foreground text-xs">{hint}</p> : null}
        </div>
        <div className="flex size-10 shrink-0 items-center justify-center rounded-2xl border bg-muted/40 text-muted-foreground">
          {icon}
        </div>
      </CardContent>
    </Card>
  );
}

function SectionShell({
  title,
  subtitle,
  icon,
  actions,
  children,
  contentClassName,
}: {
  title: string;
  subtitle?: string;
  icon: React.ReactNode;
  actions?: React.ReactNode;
  children: React.ReactNode;
  contentClassName?: string;
}) {
  return (
    <Card className="gap-0 overflow-hidden border-border/80 py-0 shadow-sm transition-shadow hover:shadow-md">
      <div className="flex flex-wrap items-center justify-between gap-3 border-b bg-muted/20 px-4 py-3.5">
        <div className="flex min-w-0 items-center gap-2.5">
          <div className="flex size-9 shrink-0 items-center justify-center rounded-xl border bg-background/80">
            {icon}
          </div>
          <div className="min-w-0">
            <p className="font-semibold text-[11px] uppercase tracking-[0.14em]">{title}</p>
            {subtitle ? <p className="mt-0.5 text-muted-foreground text-xs">{subtitle}</p> : null}
          </div>
        </div>
        {actions}
      </div>
      <CardContent className={cn("p-0", contentClassName)}>{children}</CardContent>
    </Card>
  );
}

function IncomeBreakdownTable({
  rows,
  assetTypeTitle,
}: {
  rows: Array<Record<string, unknown>>;
  assetTypeTitle: Record<string, string>;
}) {
  const columns = React.useMemo(() => {
    const keys = new Set<string>();
    for (const row of rows) {
      for (const key of Object.keys(row)) keys.add(key);
    }
    return Array.from(keys);
  }, [rows]);

  if (rows.length === 0) {
    return <p className="py-10 text-center text-muted-foreground text-sm">No income entries for this period.</p>;
  }

  return (
    <div className="overflow-x-auto">
      <Table>
        <TableHeader>
          <TableRow className="bg-muted/40 hover:bg-muted/40">
            {columns.map((col) => (
              <TableHead key={col} className="h-9 text-xs">
                {humanizeKey(col)}
              </TableHead>
            ))}
          </TableRow>
        </TableHeader>
        <TableBody>
          {rows.map((row, index) => (
            <TableRow key={index} className="hover:bg-muted/25">
              {columns.map((col) => {
                const raw = row[col];
                const display =
                  (col === "asset_type" || col === "type" || col === "product_type") &&
                  typeof raw === "string" &&
                  assetTypeTitle[raw]
                    ? assetTypeTitle[raw]
                    : raw;
                return (
                  <TableCell key={col} className="text-sm">
                    {display === null || display === undefined || display === "" ? "—" : String(display)}
                  </TableCell>
                );
              })}
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </div>
  );
}

export function PerformanceSummaryView() {
  const params = useParams<{ tenant?: string }>();
  const tenant = typeof params?.tenant === "string" && params.tenant.trim() ? params.tenant.trim() : resolveCustomerTenant();

  const [refreshKey, setRefreshKey] = React.useState(0);

  const refreshForPortfolioScope = React.useCallback(() => {
    setRefreshKey((value) => value + 1);
  }, []);
  useImpersonationScopeRefresh(refreshForPortfolioScope);

  const { data: widgetData, isLoading: widgetLoading, errorMessage: widgetError } = usePerformanceSummaryWidget(
    tenant,
    refreshKey,
  );
  const { data: reportData, isLoading: reportLoading, errorMessage: reportError } = usePerformanceSummaryReport(
    tenant,
    refreshKey,
  );
  const {
    rows: allocationRows,
    grandTotal: allocationTotal,
    reportingCurrency: allocationCurrency,
    isLoading: allocationLoading,
    errorMessage: allocationError,
  } = useAssetAllocationSummary(tenant, refreshKey);
  // Explicit user toggles only; falls back to each series' own `visible` flag when absent.
  const [hiddenOverrides, setHiddenOverrides] = React.useState<Record<string, boolean>>({});

  const isLoading = widgetLoading || reportLoading || allocationLoading;
  const errorMessage = widgetError ?? reportError;

  const series = React.useMemo(() => reportData?.serializeArra ?? [], [reportData]);
  const dateList = React.useMemo(() => reportData?.date_list ?? [], [reportData]);
  const incomeRows = React.useMemo(() => reportData?.incomeModeule ?? [], [reportData]);
  const ledgerRows = React.useMemo(
    () => (widgetData ? buildPerformanceLedgerRows(widgetData) : []),
    [widgetData],
  );
  const hasChartData = series.length > 0 && dateList.length > 0;
  const hasIncomeData = incomeRows.length > 0;

  const isSeriesHidden = React.useCallback(
    (s: (typeof series)[number]) => hiddenOverrides[s.id] ?? !s.visible,
    [hiddenOverrides],
  );

  const chartData = React.useMemo(() => buildPerformanceChartData(dateList, series), [dateList, series]);

  const lineConfig = React.useMemo(() => {
    const config: ChartConfig = {};
    series.forEach((s, index) => {
      config[s.id] = { label: s.name, color: PERFORMANCE_SERIES_COLORS[index % PERFORMANCE_SERIES_COLORS.length] };
    });
    return config;
  }, [series]);

  const toggleSeries = (s: (typeof series)[number]) => {
    setHiddenOverrides((prev) => ({ ...prev, [s.id]: !isSeriesHidden(s) }));
  };

  const currency = widgetData?.currency ?? "USD";
  const asOfLabel = widgetData?.as_of?.trim() || "—";

  return (
    <div className="flex min-w-0 flex-col gap-5">
      <div className="flex flex-col gap-3 border-b pb-4 lg:flex-row lg:items-start lg:justify-between">
        <div className="min-w-0 space-y-2">
          <div className="flex flex-wrap items-center gap-2.5">
            <div className="flex size-8 items-center justify-center rounded-lg border bg-sky-500/10 text-sky-700 dark:text-sky-400">
              <Activity className="size-4" />
            </div>
            <h1 className="font-semibold text-2xl tracking-tight leading-none">Performance Summary</h1>
            {asOfLabel !== "—" ? (
              <Badge variant="secondary" className="font-normal">
                As of {asOfLabel}
              </Badge>
            ) : null}
            {isLoading ? (
              <Badge variant="outline" className="font-normal">
                Loading…
              </Badge>
            ) : null}
          </div>
          <p className="text-muted-foreground text-sm">
            Portfolio value, equity, allocation, and performance trends
          </p>
          {errorMessage ? <p className="text-destructive text-sm">{errorMessage}</p> : null}
        </div>
        <div className="flex shrink-0 items-center gap-2">
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="outline" size="icon" className="size-9 shrink-0">
                <Download className="size-4" />
                <span className="sr-only">Download</span>
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuItem onClick={() => toast.message("PDF export", { description: "Coming soon." })}>
                Download PDF
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
          <Button
            variant="outline"
            size="icon"
            className="size-9 shrink-0"
            disabled={isLoading}
            onClick={() => setRefreshKey((k) => k + 1)}
          >
            <RefreshCw className={cn("size-4", isLoading && "animate-spin")} />
            <span className="sr-only">Refresh</span>
          </Button>
          <Button variant="outline" size="icon" className="size-9 shrink-0" asChild>
            <Link href={`/customer/${tenant}/reports`}>
              <X className="size-4" />
              <span className="sr-only">Close</span>
            </Link>
          </Button>
        </div>
      </div>

      <ReportLoadingPanel
        loading={isLoading}
        label="Loading performance summary…"
        className={cn(isLoading && "pointer-events-none")}
      >
        <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">
          <KpiCard
            label="Market value"
            value={widgetData ? formatAmountField(widgetData.market_value, currency) : "—"}
            icon={<Wallet className="size-5" />}
            hint={currency}
          />
          <KpiCard
            label="Client equity"
            value={widgetData ? formatAmountField(widgetData.client_equity, currency) : "—"}
            icon={<Scale className="size-5" />}
            hint="After loans"
          />
          <KpiCard
            label="Mark to market"
            value={widgetData ? formatAmountField(widgetData.mark_to_market, currency) : "—"}
            icon={<TrendingUp className="size-5" />}
            hint="Cost vs market"
          />
          <KpiCard
            label="Leveraged yield"
            value={widgetData ? formatReportValue(widgetData.leveraged_yield?.fmt) : "—"}
            icon={<PiggyBank className="size-5" />}
            hint="Net income / equity"
          />
        </div>

        <div className="mt-5 grid grid-cols-1 items-start gap-4 lg:grid-cols-2">
          <AssetAllocationSummaryCard
            rows={allocationRows}
            grandTotal={allocationTotal}
            reportingCurrency={allocationCurrency}
            isLoading={allocationLoading}
            errorMessage={allocationError}
          />

          <SectionShell
            title="Performance ledger"
            subtitle={`Amounts in ${currency}`}
            icon={<Activity className="size-4 text-muted-foreground" />}
          >
            {ledgerRows.length === 0 ? (
              <p className="py-16 text-center text-muted-foreground text-sm">
                No performance figures are available for this account yet.
              </p>
            ) : (
              <Table>
                <TableHeader>
                  <TableRow className="bg-muted/40 hover:bg-muted/40">
                    <TableHead className="h-9 w-10 text-center text-xs">#</TableHead>
                    <TableHead className="h-9 text-xs">Item</TableHead>
                    <TableHead className="h-9 pr-4 text-right text-xs">Amount</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {ledgerRows.map((row) => {
                    if (row.kind === "spacer") {
                      return (
                        <TableRow key={row.id} className="h-2 hover:bg-transparent">
                          <TableCell colSpan={3} className="p-0" />
                        </TableRow>
                      );
                    }
                    return (
                      <TableRow
                        key={row.id}
                        className={cn(
                          "hover:bg-muted/25",
                          row.kind === "subtotal" && "bg-muted/30 font-semibold",
                          row.kind === "total" && "bg-muted/50 font-semibold",
                        )}
                      >
                        <TableCell className="text-center text-muted-foreground text-xs tabular-nums">
                          {row.index}
                        </TableCell>
                        <TableCell className="text-sm">{row.label}</TableCell>
                        <TableCell className="pr-4 text-right text-sm tabular-nums">{row.value ?? "—"}</TableCell>
                      </TableRow>
                    );
                  })}
                </TableBody>
              </Table>
            )}
          </SectionShell>
        </div>

        {hasChartData ? (
          <div className="mt-5">
            <SectionShell
              title="Portfolio analysis"
              subtitle="Toggle series to compare performance over time"
              icon={<LineChart className="size-4 text-muted-foreground" />}
              contentClassName="p-4"
              actions={
                <Badge variant="outline" className="font-normal text-[10px] tabular-nums">
                  {series.length} series
                </Badge>
              }
            >
              <div className="mb-4 flex flex-wrap gap-1.5">
                {series.map((s) => {
                  const off = isSeriesHidden(s);
                  return (
                    <button
                      key={s.id}
                      type="button"
                      onClick={() => toggleSeries(s)}
                      className={cn(
                        "inline-flex items-center gap-1.5 rounded-md border border-border/70 bg-background px-2 py-1 text-xs transition-colors hover:bg-muted",
                        off && "opacity-40 line-through",
                      )}
                    >
                      <span
                        className="size-2.5 rounded-sm"
                        style={{ background: lineConfig[s.id]?.color as string }}
                      />
                      {s.name}
                    </button>
                  );
                })}
              </div>
              <ChartContainer config={lineConfig} className="aspect-auto h-[min(380px,50vh)] w-full">
                <RechartsLineChart data={chartData} margin={{ left: 8, right: 12, top: 8, bottom: 0 }}>
                  <CartesianGrid vertical={false} strokeDasharray="3 3" className="stroke-border/60" />
                  <XAxis dataKey="date" tickLine={false} axisLine={false} tick={{ fontSize: 11 }} />
                  <YAxis tickLine={false} axisLine={false} tick={{ fontSize: 11 }} />
                  <ChartTooltip content={<ChartTooltipContent indicator="line" />} />
                  <ChartLegend content={<ChartLegendContent />} />
                  {series.map((s) => (
                    <Line
                      key={s.id}
                      type="monotone"
                      dataKey={s.id}
                      stroke={lineConfig[s.id]?.color as string}
                      strokeWidth={2}
                      dot={false}
                      hide={isSeriesHidden(s)}
                    />
                  ))}
                </RechartsLineChart>
              </ChartContainer>
            </SectionShell>
          </div>
        ) : null}

        {hasIncomeData ? (
          <div className="mt-5">
            <SectionShell
              title="Income breakdown"
              subtitle={`${incomeRows.length} entries`}
              icon={<PiggyBank className="size-4 text-muted-foreground" />}
            >
              <IncomeBreakdownTable rows={incomeRows} assetTypeTitle={reportData?.asset_type_title ?? {}} />
            </SectionShell>
          </div>
        ) : null}
      </ReportLoadingPanel>
    </div>
  );
}
