"use client";

import * as React from "react";

import { Skeleton } from "@/components/ui/skeleton";
import { cn } from "@/lib/utils";
import { customerUrl } from "@/lib/tenant";

import { FiguresMaskedContext } from "@/app/customer/_components/dashboard-overview-layout";
import { LoanDetailSheet } from "@/app/customer/_components/loan-detail-sheet";
import { DashboardWidgetBody } from "@/app/customer/_components/dashboard-charts/dashboard-widget-body";
import type { DashboardBarItem } from "@/app/customer/_components/dashboard-charts/types";
import { DashboardWidgetShell } from "@/app/customer/_components/dashboard-widget-shell";
import { LAYOUT_IDS } from "@/app/customer/_lib/dashboard-layout";
import { useDashboardWidgetData } from "@/app/customer/_lib/use-dashboard-widget-data";
import { getStaticWidgetDefinition } from "@/app/customer/_lib/dashboard-widget-registry-definitions";
import { buildPerformanceMetricBars } from "@/app/customer/[tenant]/reports/performance-summary/_lib/performance-chart-data";
import { fetchPerformanceSummaryWidgetClient } from "@/app/customer/[tenant]/reports/performance-summary/_lib/performance-summary-api";
import type { PerformanceSummaryWidgetData } from "@/app/customer/[tenant]/reports/performance-summary/_lib/performance-summary-types";

const widgetMeta = getStaticWidgetDefinition("performance");

// Temporarily hidden sections — flip to true to bring them back.
const SHOW_KPI_STRIP = false;
const SHOW_METRIC_COMPARISON = false;

function isZero(raw: number) {
  return !Number.isFinite(raw) || Math.abs(raw) < 1e-9;
}

function numClass(raw: number) {
  return raw < 0 ? "text-red-600 dark:text-red-400" : "text-emerald-700 dark:text-emerald-400";
}

function KpiCell({
  label,
  value,
  visible,
  highlight,
  dense,
}: {
  label: string;
  value: React.ReactNode;
  visible: boolean;
  highlight?: boolean;
  dense?: boolean;
}) {
  const figuresMasked = React.useContext(FiguresMaskedContext);
  if (!visible) return null;
  return (
    <div className={cn("bg-card", dense ? "px-3 py-2" : "px-3.5 py-2.5")}>
      <p
        className={cn(
          "font-semibold uppercase tracking-wide text-muted-foreground",
          dense ? "text-[9px]" : "text-[10px]",
        )}
      >
        {label}
      </p>
      <p
        className={cn(
          "mt-0.5 truncate font-bold tabular-nums text-foreground",
          dense ? "text-[13px]" : "text-sm",
          highlight && "text-primary",
        )}
      >
        {figuresMasked ? "*******" : value}
      </p>
    </div>
  );
}

function KpiStrip({
  data,
  currency,
  dense,
}: {
  data: PerformanceSummaryWidgetData;
  currency: string;
  dense?: boolean;
}) {
  const cells = [
    {
      key: "cost",
      label: "Investment Cost",
      value: `${currency} ${data.investment_cost.fmt}`,
      visible: !isZero(data.investment_cost.raw),
    },
    {
      key: "equity",
      label: "Client Equity",
      value: `${currency} ${data.client_equity.fmt}`,
      visible: !isZero(data.client_equity.raw),
    },
    {
      key: "income",
      label: "Income Potential",
      value: `${currency} ${data.gross_income.fmt}`,
      visible: !isZero(data.gross_income.raw),
    },
    {
      key: "yield",
      label: "Leveraged Yield",
      value: (
        <span
          className={cn(
            "inline-flex items-center rounded-full bg-emerald-600 text-white",
            dense ? "px-1.5 py-0.5 text-[10px]" : "px-2 py-0.5 text-xs",
          )}
        >
          {data.leveraged_yield.fmt}
        </span>
      ),
      visible: !isZero(data.leveraged_yield.raw),
      highlight: true,
    },
  ].filter((cell) => cell.visible);

  if (cells.length === 0) return null;

  return (
    <div className="grid shrink-0 grid-cols-2 divide-x divide-y border-b">
      {cells.map((cell) => (
        <KpiCell
          key={cell.key}
          label={cell.label}
          value={cell.value}
          visible
          highlight={cell.highlight}
          dense={dense}
        />
      ))}
    </div>
  );
}

/** Compact bars for metric-vs-cost — same values as buildPerformanceMetricBars. */
function MetricComparison({
  items,
  costLabel,
  dense = false,
}: {
  items: DashboardBarItem[];
  costLabel: string;
  dense?: boolean;
}) {
  const figuresMasked = React.useContext(FiguresMaskedContext);
  if (items.length === 0) return null;

  // Bar width uses the same % of cost; allow >100% to show without clipping the track.
  const maxPct = Math.max(100, ...items.map((item) => item.value));

  return (
    <div
      className={cn(
        "rounded-xl bg-muted/30",
        dense ? "p-2.5" : "p-3",
      )}
    >
      <div className={cn("flex items-center justify-between gap-2", dense ? "mb-2" : "mb-2.5")}>
        <p className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">
          {dense ? "Vs cost" : "Relative to investment cost"}
        </p>
        {costLabel ? (
          <p className="truncate text-[10px] text-muted-foreground tabular-nums">{costLabel}</p>
        ) : null}
      </div>
      <div className={cn(dense ? "space-y-2" : "space-y-2.5")}>
        {items.map((item) => {
          const widthPct = maxPct > 0 ? Math.min(100, (item.value / maxPct) * 100) : 0;
          const amountPart = item.formatted?.replace(/\s*\([^)]*%\)\s*$/, "").trim() ?? "";
          return (
            <div key={item.id} className="space-y-1">
              <div className="flex items-baseline justify-between gap-2 text-xs">
                <span className="inline-flex min-w-0 items-center gap-1.5 font-medium text-foreground">
                  <span
                    className="size-2 shrink-0 rounded-sm"
                    style={{ background: item.fill ?? "var(--chart-1)" }}
                    aria-hidden
                  />
                  <span className="truncate">{item.name}</span>
                </span>
                <span className="shrink-0 tabular-nums text-muted-foreground">
                  {figuresMasked ? (
                    "*******"
                  ) : dense ? (
                    <span className="text-[11px] font-semibold text-foreground/80">
                      {item.value.toFixed(1)}%
                    </span>
                  ) : (
                    <>
                      <span className="font-medium text-foreground">{amountPart}</span>
                      <span className="ml-1.5 text-[10px] font-semibold text-foreground/70">
                        {item.value.toFixed(1)}%
                      </span>
                    </>
                  )}
                </span>
              </div>
              <div className="h-2 overflow-hidden rounded-full bg-background">
                <div
                  className="h-full rounded-full transition-[width] duration-300"
                  style={{
                    width: `${widthPct}%`,
                    background: item.fill ?? "var(--chart-1)",
                  }}
                />
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

/** Ledger is not scrollable itself — parent owns one clear overflow. */
function PerformanceLedger({
  data,
  currency,
}: {
  data: PerformanceSummaryWidgetData;
  currency: string;
}) {
  const [loanCurrency, setLoanCurrency] = React.useState<string | null>(null);
  const selectedLoan = data.loans.find((loan) => loan.currency === loanCurrency) ?? null;

  return (
    <div className="text-xs">
      <WidgetSection title="Portfolio">
        <WidgetRow
          label="Investment Cost"
          value={`${currency} ${data.investment_cost.fmt}`}
          raw={data.investment_cost.raw}
        />
        <WidgetRow
          label="Market Value (RC)"
          value={`${currency} ${data.market_value.fmt}`}
          raw={data.market_value.raw}
        />
        <WidgetRow
          label="Accrued Interest"
          value={`${currency} ${data.accrued_interest.fmt}`}
          raw={data.accrued_interest.raw}
        />
        <WidgetRow
          label="Mark to Market"
          hint="Market Value + Accrued Interest − Investment Cost"
          value={`${currency} ${data.mark_to_market.fmt}`}
          raw={data.mark_to_market.raw}
        />
      </WidgetSection>

      {!isZero(data.total_loan.raw) ? (
        <WidgetSection title="Loans">
          {data.loans
            .filter((loan) => !isZero(loan.amount))
            .map((loan) => (
              <WidgetRow
                key={loan.currency}
                label={`Loan (${loan.currency})`}
                value={`${currency} ${loan.formatted}`}
                raw={loan.amount}
                negative
                onClick={() => setLoanCurrency(loan.currency)}
              />
            ))}
          <WidgetRow
            label="Total Loan"
            value={`${currency} ${data.total_loan.fmt}`}
            raw={data.total_loan.raw}
            negative
            subtotal
          />
        </WidgetSection>
      ) : null}

      <WidgetSection title="Equity & Income">
        <WidgetRow
          label="Client Equity"
          hint="Market Value − Total Loan"
          value={`${currency} ${data.client_equity.fmt}`}
          raw={data.client_equity.raw}
        />
        {!isZero(data.gross_income.raw) ? (
          <WidgetRow
            label="Indicative Gross Income Potential"
            hint={`All income received, in ${currency} at current rates`}
            value={`${currency} ${data.gross_income.fmt}`}
            raw={data.gross_income.raw}
          />
        ) : null}
      </WidgetSection>

      <LoanDetailSheet
        loan={selectedLoan}
        reportingCurrency={currency}
        asOf={data.as_of}
        onClose={() => setLoanCurrency(null)}
      />
    </div>
  );
}

function PerformanceWidgetBody({
  data,
  currency,
}: {
  data: PerformanceSummaryWidgetData;
  currency: string;
}) {
  const metricBars = React.useMemo(() => buildPerformanceMetricBars(data), [data]);
  const costLabel = !isZero(data.investment_cost.raw)
    ? `${currency} ${data.investment_cost.fmt} = 100%`
    : "";

  return (
    <DashboardWidgetBody>
      {({ tier, width, height }) => {
        const dense = tier === "compact" || width < 360;
        const sideBySide =
          SHOW_METRIC_COMPARISON && tier === "expanded" && width >= 640 && height >= 360;

        if (sideBySide) {
          return (
            <div className="flex min-h-0 flex-1 flex-col overflow-hidden">
              {SHOW_KPI_STRIP ? <KpiStrip data={data} currency={currency} /> : null}
              <div className="grid min-h-0 flex-1 grid-cols-2 gap-3 overflow-hidden p-3 sm:p-4">
                <div className="min-h-0 overflow-y-auto pr-1">
                  <MetricComparison items={metricBars} costLabel={costLabel} />
                </div>
                <div className="min-h-0 overflow-y-auto pr-1">
                  <PerformanceLedger data={data} currency={currency} />
                </div>
              </div>
            </div>
          );
        }

        return (
          <div className="flex min-h-0 flex-1 flex-col overflow-hidden">
            {SHOW_KPI_STRIP ? <KpiStrip data={data} currency={currency} dense={dense} /> : null}
            {/* One scroll for bars + full ledger at every size. */}
            <div
              className={cn(
                "min-h-0 flex-1 space-y-3 overflow-y-auto",
                dense ? "p-3 pb-4" : "p-3 pb-4 sm:p-4",
              )}
            >
              {SHOW_METRIC_COMPARISON ? (
                <MetricComparison items={metricBars} costLabel={costLabel} dense={dense} />
              ) : null}
              <PerformanceLedger data={data} currency={currency} />
            </div>
          </div>
        );
      }}
    </DashboardWidgetBody>
  );
}

export function PerformanceSummaryWidget() {
  const fetchIndividual = React.useCallback(async (resolvedTenant: string) => {
    const result = await fetchPerformanceSummaryWidgetClient(resolvedTenant);
    return { data: result.data, errorMessage: result.errorMessage };
  }, []);

  const { tenant, data, loading, refreshing, error, refresh } = useDashboardWidgetData<PerformanceSummaryWidgetData>({
    layoutId: LAYOUT_IDS.performance,
    fetchIndividual,
    refreshOnScopeChange: false,
  });

  const currency = data?.currency ?? "USD";
  const reportHref = customerUrl(tenant, widgetMeta.reportPath ?? "/reports/performance-summary");

  return (
    <DashboardWidgetShell
      title={widgetMeta.label}
      subtitle={data?.as_of ? `As of ${data.as_of}` : undefined}
      reportHref={reportHref}
      loading={loading && !data}
      refreshing={refreshing}
      error={error}
      onRefresh={refresh}
      loadingContent={
        <div className="flex flex-1 flex-col gap-3 p-4">
          <div className="grid grid-cols-2 divide-x divide-y border-b">
            {Array.from({ length: 4 }).map((_, i) => (
              <Skeleton key={i} className="h-14 rounded-none" />
            ))}
          </div>
          <Skeleton className="h-24 w-full rounded-xl" />
          <div className="space-y-2">
            {Array.from({ length: 4 }).map((_, i) => (
              <Skeleton key={i} className="h-4 w-full" />
            ))}
          </div>
        </div>
      }
    >
      {data ? <PerformanceWidgetBody data={data} currency={currency} /> : null}
    </DashboardWidgetShell>
  );
}

function WidgetSection({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <div className="mb-3 last:mb-0">
      <div className="mb-1.5 flex items-center gap-2 text-[10px] font-bold uppercase tracking-wide text-primary">
        <span>{title}</span>
        <span className="h-px flex-1 bg-border" />
      </div>
      <div className="divide-y">{children}</div>
    </div>
  );
}

function WidgetRow({
  label,
  hint,
  value,
  raw,
  negative,
  subtotal,
  onClick,
}: {
  label: string;
  hint?: string;
  value: string;
  raw: number;
  negative?: boolean;
  subtotal?: boolean;
  onClick?: () => void;
}) {
  const figuresMasked = React.useContext(FiguresMaskedContext);
  if (isZero(raw)) return null;
  const Comp = onClick ? "button" : "div";
  return (
    <Comp
      type={onClick ? "button" : undefined}
      onClick={onClick}
      className={cn(
        "flex w-full items-center justify-between gap-3 py-1.5 text-left",
        subtotal && "rounded bg-muted/40 px-2 font-semibold",
        onClick && "cursor-pointer hover:bg-muted/50 hover:underline underline-offset-2",
      )}
    >
      <span className="min-w-0 text-foreground/80">
        <span className="block truncate">{label}</span>
        {hint ? <span className="block truncate text-[10px] text-muted-foreground">{hint}</span> : null}
      </span>
      <span
        className={cn(
          "shrink-0 tabular-nums",
          negative ? "text-red-600 dark:text-red-400" : numClass(raw),
        )}
      >
        {figuresMasked ? "*******" : value}
      </span>
    </Comp>
  );
}
