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

/**
 * Organism — "Top 3 Loans Available" section for the Borrowing Capacity page.
 *
 * Layout:
 * - Heading row: "Top 3 Loans Available" (left) + "See All Options" link (right)
 * - Two-column body:
 *   - Left: up to 3 `TopThreeProductItem` rows (lender logo, rate, max loan, repayment)
 *   - Right: Outcome panel (descriptive text + CTA buttons)
 *
 * All values are pre-formatted / typed — business logic stays in the app layer.
 */

// ─── Sub-types ───────────────────────────────────────────────────────────────

export interface TopThreeProductItem {
  /** Lender display name (e.g. "ANZ") */
  lender: string;
  /** URL for the lender logo image. Falls back to initials if omitted. */
  lenderLogoUrl?: string;
  /** Interest rate as a percentage (e.g. 5.5 → displayed as "5.50%") */
  interestRate: number;
  /** true = Variable rate, false = Fixed rate */
  isVariable: boolean;
  /** Maximum loan amount in AUD dollars */
  maxLoanAmount: number;
  /** Monthly repayment in AUD dollars */
  monthlyRepayment: number;
}

export interface TopThreeProductProps {
  /** Up to 3 loan products to display */
  items?: TopThreeProductItem[];
  /** Outcome summary text shown in the right panel */
  outcomeText?: string;
  /** Called when "See All Options" is clicked */
  onSeeAllOptions?: () => void;
  /** Called when "Talk To Your Broker" CTA is clicked */
  onTalkToBroker?: () => void;
  /** Called when "Start Loan Application" CTA is clicked */
  onStartLoanApplication?: () => void;
  /** Replace content with a skeleton loading state */
  isLoading?: boolean;
  className?: string;
}

// ─── Internal stat cell ──────────────────────────────────────────────────────

function StatCell({ value, label }: { value: React.ReactNode; label: string }) {
  return (
    <div className="flex flex-col items-center gap-0.5 text-center">
      <span className="text-base font-semibold tabular-nums text-foreground">
        {value}
      </span>
      <span className="text-xs text-muted-foreground">{label}</span>
    </div>
  );
}

// ─── Internal product row ─────────────────────────────────────────────────────

function ProductRow({ item }: { item: TopThreeProductItem }) {
  const initials = item.lender
    .split(" ")
    .map((w) => w[0])
    .slice(0, 2)
    .join("");

  return (
    <div className="flex items-center gap-4 py-3">
      {/* Lender logo / initials fallback */}
      <div className="flex h-10 w-10 shrink-0 items-center justify-center border border-border bg-muted text-xs font-semibold text-muted-foreground">
        {item.lenderLogoUrl ? (
          <img
            src={item.lenderLogoUrl}
            alt={item.lender}
            className="h-full w-full object-contain"
          />
        ) : (
          initials
        )}
      </div>

      {/* Stats — rate, max loan, repayment */}
      <div className="flex flex-1 items-center justify-between gap-2">
        <StatCell
          value={`${item.interestRate.toFixed(2)}%`}
          label={item.isVariable ? "Variable" : "Fixed"}
        />
        <StatCell
          value={formatCurrency(item.maxLoanAmount)}
          label="Max Loan Amount"
        />
        <StatCell
          value={formatCurrency(item.monthlyRepayment)}
          label="Monthly Repayments"
        />
      </div>
    </div>
  );
}

// ─── Main component ───────────────────────────────────────────────────────────

export function TopThreeProduct({
  items = [],
  outcomeText,
  onSeeAllOptions,
  onTalkToBroker,
  onStartLoanApplication,
  isLoading = false,
  className,
}: TopThreeProductProps) {
  const showOutcome = Boolean(
    outcomeText || onTalkToBroker || onStartLoanApplication,
  );

  return (
    <div className={cn("flex flex-col gap-3", className)}>
      {/* Heading row */}
      <div className="flex items-center justify-between">
        <span className="text-sm font-semibold text-foreground">
          Top 3 Loans Available
        </span>
        {onSeeAllOptions && (
          <button
            type="button"
            onClick={onSeeAllOptions}
            className="flex items-center gap-1 text-sm text-primary transition-opacity hover:opacity-70"
          >
            See All Options
            <ChevronRight size={14} className="shrink-0" />
          </button>
        )}
      </div>

      {/* Body — products + outcome */}
      <div className="flex gap-4">
        {/* Product list */}
        <div className="flex flex-1 flex-col divide-y divide-border">
          {isLoading
            ? Array.from({ length: 3 }).map((_, i) => (
                <div key={i} className="flex items-center gap-4 py-3">
                  <Skeleton className="h-10 w-10 shrink-0" />
                  <div className="flex flex-1 justify-between gap-4">
                    <Skeleton className="h-8 w-16" />
                    <Skeleton className="h-8 w-20" />
                    <Skeleton className="h-8 w-20" />
                  </div>
                </div>
              ))
            : items.length > 0
              ? items
                  .slice(0, 3)
                  .map((item, i) => (
                    <ProductRow key={`${item.lender}-${i}`} item={item} />
                  ))
              : !isLoading && (
                  <p className="py-6 text-center text-sm text-muted-foreground">
                    No lender options available for this scenario.
                  </p>
                )}
        </div>

        {/* Outcome panel */}
        {showOutcome && (
          <div className="flex w-48 shrink-0 flex-col gap-3 border-l border-border pl-4">
            <span className="text-sm font-semibold uppercase tracking-wide text-muted-foreground">
              Outcome
            </span>
            {outcomeText && (
              <p className="text-sm text-foreground">{outcomeText}</p>
            )}
            <div className="flex flex-col gap-2">
              {onTalkToBroker && (
                <Button
                  variant="default"
                  size="sm"
                  onClick={onTalkToBroker}
                  className="w-full"
                >
                  Talk To Your Broker
                </Button>
              )}
              {onStartLoanApplication && (
                <Button
                  variant="outline"
                  size="sm"
                  onClick={onStartLoanApplication}
                  className="w-full"
                >
                  Start Loan Application
                </Button>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
