import React from "react";
import { cn } from "@/lib/utils";
import {
  BorrowCapacityItem,
  StatisticItem,
  LoanToValueRatio,
} from "./borrowing-capacity-atoms";
import { BorrowingCapacityLineChart } from "./borrowing-capacity-line-chart";
import type { BorrowingCapacitySeries } from "./borrowing-capacity-line-chart";
import { Skeleton } from "./skeleton";

/**
 * Main content organism for the Borrowing Capacity page.
 *
 * Composes (top-to-bottom):
 * - `BorrowingCapacityLineChart` — full-width chart with KPI header
 * - Key metrics grid — flexible list of `BorrowCapacityItem` fields
 * - LVR panel (optional) — `LoanToValueRatio` pinned to the right of metrics
 * - Statistics row — up to 3 `StatisticItem` trend blocks
 *
 * All values are pre-formatted strings / cents — business logic stays in the
 * app layer. Pass `isLoading` to switch every section into skeleton state.
 */

export interface BorrowingCapacityCardField {
  /** e.g. "Purchase Price" */
  label: string;
  /** Optional secondary descriptor, e.g. "80% LVR" */
  subLabel?: string;
  /** Pre-formatted value, e.g. "$750,000" */
  value: string;
}

export interface BorrowingCapacityCardStatistic {
  /** Number of months to look back (e.g. 3, 6, 12) */
  loopBackMonths: number;
  /** Absolute dollar change over the period */
  amountChange: number;
  /** Percentage change — positive = up, negative = down, 0 = flat */
  amountChangePercentage: number;
}

export interface BorrowingCapacityCardProps {
  // ── Chart ─────────────────────────────────────────────────────────────────
  /** Data series to render in the line chart */
  chartSeries?: BorrowingCapacitySeries[] | null;
  /** Current borrowing capacity in AUD cents — shown as KPI in the chart header */
  kpiValueCents?: number;

  // ── Key metrics ───────────────────────────────────────────────────────────
  /** Ordered result fields rendered in a responsive grid (max 4 per row) */
  fields?: BorrowingCapacityCardField[];

  // ── LVR ───────────────────────────────────────────────────────────────────
  /** LVR as a whole number percentage (0–100). Omit to hide the LVR panel. */
  lvr?: number;
  debtAmount?: number;
  equityAmount?: number;

  // ── Statistics ────────────────────────────────────────────────────────────
  /** Trend blocks shown below the metrics (typically 3 periods: 3, 6, 12 mo) */
  statistics?: BorrowingCapacityCardStatistic[];

  // ── State ─────────────────────────────────────────────────────────────────
  /** Show skeleton loading state across every section */
  isLoading?: boolean;

  className?: string;
}

export function BorrowingCapacityCard({
  chartSeries,
  kpiValueCents,
  fields,
  lvr,
  debtAmount,
  equityAmount,
  statistics,
  isLoading = false,
  className,
}: BorrowingCapacityCardProps) {
  const hasFields = (fields?.length ?? 0) > 0;
  const hasLvr = lvr !== undefined;
  const hasStats = (statistics?.length ?? 0) > 0;
  const showMetricsRow = isLoading || hasFields || hasLvr;
  const showStatsRow = isLoading || hasStats;

  return (
    <div className={cn("flex flex-col border border-border", className)}>
      {/* Chart — border stripped so the organism border acts as the card edge */}
      <BorrowingCapacityLineChart
        series={chartSeries}
        kpiValue={kpiValueCents}
        isLoading={isLoading}
        className="border-0 shadow-none"
      />

      {/* Key metrics + optional LVR panel */}
      {showMetricsRow && (
        <div className="flex items-stretch border-t border-border">
          <div className="grid flex-1 grid-cols-4 gap-x-6 gap-y-4 p-4">
            {isLoading
              ? Array.from({ length: fields?.length ?? 4 }).map((_, i) => (
                  <div key={i} className="flex flex-col gap-1.5">
                    <Skeleton className="h-10 w-full" />
                    <Skeleton className="h-6 w-28" />
                  </div>
                ))
              : fields?.map((field, i) => (
                  <BorrowCapacityItem
                    key={i}
                    title={field.label}
                    subTitle={field.subLabel}
                    value={field.value}
                  />
                ))}
          </div>

          {/* LVR — right-pinned column, w-48 keeps Debt/Equity on one line */}
          {(isLoading || hasLvr) && (
            <div className="flex w-48 shrink-0 items-center border-l border-border p-4">
              {isLoading ? (
                <div className="flex w-full flex-col items-center gap-2">
                  <Skeleton className="h-10 w-14" />
                  <Skeleton className="h-2 w-full" />
                  <Skeleton className="h-4 w-full" />
                </div>
              ) : (
                <LoanToValueRatio
                  lvr={lvr!}
                  debtAmount={debtAmount}
                  equityAmount={equityAmount}
                  className="w-full"
                />
              )}
            </div>
          )}
        </div>
      )}

      {/* Statistics row */}
      {showStatsRow && (
        <div className="flex gap-3 border-t border-border p-4">
          {isLoading
            ? Array.from({ length: statistics?.length ?? 3 }).map((_, i) => (
                <Skeleton key={i} className="h-16 flex-1" />
              ))
            : statistics?.map((stat, i) => (
                <StatisticItem key={i} {...stat} className="flex-1" />
              ))}
        </div>
      )}
    </div>
  );
}
