import React, { useState } from "react";
import { cn } from "@/lib/utils";
import { formatCurrency, formatCurrencyAbbrev } from "@/lib/format-currency";
import { Button } from "./button";
import { Skeleton } from "./skeleton";

/**
 * Organism — full lender comparison table for the Borrowing Capacity page.
 *
 * Renders an optional title, a sticky column-header row, and a paginated list
 * of lender rows. Each row shows: Lender, Interest Rate, Comparison Rate,
 * Monthly Repayments, Total Cost, and Max Buying Power.
 *
 * Values are pre-formatted / typed — business logic stays in the app layer.
 * Pass `isLoading` to render a skeleton table in place of real rows.
 */

export interface InterestRateItem {
  /** Lender display name (e.g. "ANZ") */
  lender: string;
  /** Interest rate percentage (e.g. 5.5 → displayed as "5.50%") */
  interestRate: number;
  /** Comparison rate percentage (e.g. 5.75 → displayed as "5.75%") */
  comparisonRate: number;
  /** Pre-formatted monthly repayment string (e.g. "$2,800" or "$2,800 – $3,100") */
  monthlyRepayment: string;
  /** Total cost in AUD cents */
  totalCost: number;
  /** Maximum buying power in AUD cents */
  maxBuyingPower: number;
}

export interface InterestRateSectionProps {
  /**
   * Section heading shown above the table, e.g.
   * "Lender Options for cash towards $150,000"
   */
  title?: string;
  /** Lender rows to display */
  items?: InterestRateItem[];
  /** Number of rows shown per page (default: 5) */
  pageSize?: number;
  /** Replace rows with a skeleton loading state */
  isLoading?: boolean;
  className?: string;
}

const COLUMN_HEADERS = [
  "Lender",
  "Interest Rate",
  "Comparison Rate",
  "Monthly Repayments",
  "Total Cost",
  "Real Buying Power",
] as const;

export function InterestRateSection({
  title,
  items = [],
  pageSize = 5,
  isLoading = false,
  className,
}: InterestRateSectionProps) {
  const [visibleCount, setVisibleCount] = useState(pageSize);
  const visibleItems = items.slice(0, visibleCount);
  const hasMore = visibleCount < items.length;

  const handleLoadMore = () => setVisibleCount((n) => n + pageSize);

  return (
    <div className={cn("flex flex-col gap-3", className)}>
      {title && (
        <p className="text-sm font-semibold text-foreground">{title}</p>
      )}

      {/* Column headers */}
      <div className="grid grid-cols-6 border-b border-border pb-2">
        {COLUMN_HEADERS.map((col) => (
          <span
            key={col}
            className="text-xs font-medium uppercase tracking-wide text-muted-foreground"
          >
            {col}
          </span>
        ))}
      </div>

      {/* Rows */}
      <div className="flex flex-col divide-y divide-border">
        {isLoading
          ? Array.from({ length: pageSize }).map((_, i) => (
              <div key={i} className="grid grid-cols-6 gap-2 py-3">
                {Array.from({ length: 6 }).map((__, j) => (
                  <Skeleton key={j} className="h-4 w-full" />
                ))}
              </div>
            ))
          : visibleItems.length > 0
            ? visibleItems.map((item, i) => (
                <div
                  key={`${item.lender}-${i}`}
                  className="grid grid-cols-6 items-center py-3"
                >
                  {/* Lender */}
                  <div className="flex items-center gap-2">
                    <span
                      className="h-2 w-2 shrink-0 rounded-full bg-primary"
                      aria-hidden
                    />
                    <span className="truncate text-sm font-medium text-foreground">
                      {item.lender}
                    </span>
                  </div>

                  {/* Interest Rate */}
                  <span className="text-sm tabular-nums text-foreground">
                    {item.interestRate.toFixed(2)}%
                  </span>

                  {/* Comparison Rate */}
                  <span className="text-sm tabular-nums text-foreground">
                    {item.comparisonRate.toFixed(2)}%
                  </span>

                  {/* Monthly Repayments */}
                  <span className="text-sm text-foreground">
                    {item.monthlyRepayment}
                  </span>

                  {/* Total Cost */}
                  <span className="text-sm tabular-nums text-foreground">
                    {formatCurrencyAbbrev(item.totalCost)}
                  </span>

                  {/* Max Buying Power */}
                  <span className="text-sm font-semibold tabular-nums text-foreground">
                    {formatCurrency(item.maxBuyingPower)}
                  </span>
                </div>
              ))
            : !isLoading && (
                <p className="py-6 text-center text-sm text-muted-foreground">
                  No lender options available for this scenario.
                </p>
              )}
      </div>

      {/* Load more */}
      {!isLoading && hasMore && (
        <div className="flex justify-center pt-1">
          <Button variant="outline" size="sm" onClick={handleLoadMore}>
            Load More
          </Button>
        </div>
      )}
    </div>
  );
}
