"use client";

import * as React from "react";

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

import { DashboardWidgetBody } from "@/app/customer/_components/dashboard-charts/dashboard-widget-body";
import { ResponsiveHorizontalBarChart } from "@/app/customer/_components/dashboard-charts/responsive-horizontal-bar-chart";
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");

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,
}: {
  label: string;
  value: React.ReactNode;
  visible: boolean;
  highlight?: boolean;
}) {
  if (!visible) return null;
  return (
    <div className="bg-card px-3.5 py-2.5">
      <p className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">{label}</p>
      <p className={cn("mt-0.5 truncate text-sm font-bold tabular-nums text-foreground", highlight && "text-primary")}>{value}</p>
    </div>
  );
}

function PerformanceLedger({ data, currency, condensed = false }: { data: PerformanceSummaryWidgetData; currency: string; condensed?: boolean }) {
  return (
    <div className={cn("min-h-0 flex-1 overflow-y-auto text-xs", condensed && "max-h-[200px]")}>
      <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} />
        {!condensed ? (
          <>
            <WidgetRow label="Accrued Interest" value={`${currency} ${data.accrued_interest.fmt}`} raw={data.accrued_interest.raw} />
            <WidgetRow
              label="Mark to Market (2+3−1)"
              value={`${currency} ${data.mark_to_market.fmt}`}
              raw={data.mark_to_market.raw}
            />
          </>
        ) : null}
      </WidgetSection>

      {!condensed && !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={loan.formatted}
                raw={loan.amount}
                negative
              />
            ))}
          <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 (2 − Total Loan)"
          value={`${currency} ${data.client_equity.fmt}`}
          raw={data.client_equity.raw}
        />
        {!isZero(data.gross_income.raw) ? (
          <WidgetRow
            label="Indicative Gross Income Potential"
            value={`${currency} ${data.gross_income.fmt}`}
            raw={data.gross_income.raw}
          />
        ) : null}
      </WidgetSection>
    </div>
  );
}

function PerformanceWidgetBody({
  data,
  currency,
}: {
  data: PerformanceSummaryWidgetData;
  currency: string;
}) {
  const metricBars = React.useMemo(() => buildPerformanceMetricBars(data), [data]);

  const kpiVisible =
    !(
      isZero(data.investment_cost.raw) &&
      isZero(data.client_equity.raw) &&
      isZero(data.gross_income.raw) &&
      isZero(data.leveraged_yield.raw)
    );

  const kpiToolbar = kpiVisible ? (
    <div className="grid grid-cols-2 divide-x divide-y border-b">
      <KpiCell
        label="Investment Cost"
        value={`${currency} ${data.investment_cost.fmt}`}
        visible={!isZero(data.investment_cost.raw)}
      />
      <KpiCell
        label="Client Equity"
        value={`${currency} ${data.client_equity.fmt}`}
        visible={!isZero(data.client_equity.raw)}
      />
      <KpiCell
        label="Income Potential"
        value={`${currency} ${data.gross_income.fmt}`}
        visible={!isZero(data.gross_income.raw)}
      />
      <KpiCell
        label="Leveraged Yield"
        value={
          <span className="inline-flex items-center rounded-full bg-emerald-600 px-2 py-0.5 text-xs text-white">
            {data.leveraged_yield.fmt}
          </span>
        }
        visible={!isZero(data.leveraged_yield.raw)}
        highlight
      />
    </div>
  ) : null;

  return (
    <DashboardWidgetBody>
      {({ tier }) => {
        if (tier === "compact") {
          return (
            <div className="overflow-y-auto p-4">
              <PerformanceLedger data={data} currency={currency} condensed />
            </div>
          );
        }

        if (tier === "balanced") {
          return (
            <>
              {kpiToolbar}
              <div className="flex min-h-0 flex-1 flex-col gap-3 overflow-hidden p-4">
                {metricBars.length > 0 ? (
                  <ResponsiveHorizontalBarChart
                    items={metricBars}
                    height={160}
                    valueFormatter={(item) => item.formatted ?? `${item.value.toFixed(1)}%`}
                  />
                ) : null}
                <PerformanceLedger data={data} currency={currency} condensed />
              </div>
            </>
          );
        }

        return (
          <>
            {kpiToolbar}
            <div className="grid min-h-0 flex-1 grid-cols-[minmax(200px,0.9fr)_minmax(0,1.1fr)] gap-3 overflow-hidden p-4">
              <ResponsiveHorizontalBarChart
                items={metricBars}
                valueFormatter={(item) => item.formatted ?? `${item.value.toFixed(1)}%`}
              />
              <PerformanceLedger data={data} currency={currency} />
            </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>
          <div className="space-y-2">
            {Array.from({ length: 5 }).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">
      <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,
  value,
  raw,
  negative,
  subtotal,
}: {
  label: string;
  value: string;
  raw: number;
  negative?: boolean;
  subtotal?: boolean;
}) {
  if (isZero(raw)) return null;
  return (
    <div
      className={cn(
        "flex items-center justify-between gap-3 py-1.5",
        subtotal && "rounded bg-muted/40 px-2 font-semibold",
      )}
    >
      <span className="text-foreground/80">{label}</span>
      <span className={cn("shrink-0 tabular-nums", negative ? "text-red-600 dark:text-red-400" : numClass(raw))}>
        {value}
      </span>
    </div>
  );
}
