import * as React from "react";
import {
  Baby,
  Building2,
  Car,
  ChevronDown,
  CreditCard,
  Dumbbell,
  GraduationCap,
  HeartPulse,
  Landmark,
  Receipt,
  RefreshCw,
  Shield,
  ShoppingCart,
  Shirt,
  Tv,
  UtensilsCrossed,
  Zap,
} from "lucide-react";
import type { LucideIcon } from "lucide-react";
import { cn } from "@/lib/utils";
import { formatDateShort } from "@/lib/format-date";
import { Badge } from "./badge";
import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "./accordion";
import { RadioGroup, RadioGroupItem } from "./radio-group";
import {
  FinancialDetailField,
  FinancialLineItem,
  FinancialLvrBar,
  FinancialSubsectionTitle,
  FinancialSubtotalBlock,
  FinancialSubtotalFrame,
} from "./financial-primitives";
import { Button } from "./button";

/**
 * Financial card molecules — WealthX DS  (Level 3)
 *
 * Composed from financial primitives (Level 2) + shadcn atoms.
 * Used inside summary report drawers, opportunity detail panels,
 * and any financial data section in the backoffice.
 *
 * Component inventory:
 *   PropertyCard        — property holding with optional bank link + expandable loan detail
 *   DebtCard            — mortgage / investment-loan breakdown
 *   OtherLiabilityCard  — credit card or personal loan card (discriminated by `type`)
 *   AlertCard           — single alert item with severity indicator + dismiss/snooze actions
 */

// ---------------------------------------------------------------------------
// PropertyCard
// ---------------------------------------------------------------------------

export interface PropertyCardProps {
  /** Street address or property name */
  address: string;
  /** Badge label: "Owner Occupier", "Investment", etc. */
  type?: string;
  /** Estimated property value e.g. "$1,200,000" */
  estimated: string;
  /**
   * When true removes the outer card border.
   * Use inside `FinancialViewSection` where the card is already inside a bordered container.
   */
  borderless?: boolean;

  /** Whether a bank mortgage account is linked to this property */
  isLinkedToBank?: boolean;
  /** Outstanding loan amount — only shown when isLinkedToBank */
  loanAmount?: string;
  /** Equity = estimated − loan — only shown when isLinkedToBank */
  equity?: string;
  /** LVR label e.g. "56% — Good" — only shown when isLinkedToBank */
  lvr?: string;
  /** LVR numeric percentage (drives color thresholds) */
  lvrPercent?: number;

  // — Expandable loan detail (visible only when isLinkedToBank && expanded) —
  lenderName?: string;
  interestRate?: string;
  yearsRemaining?: string;
  minRepayments?: string;
  averageRepayments?: string;
  redrawAmount?: string;
  offsetAccount?: string;

  // — SubtotalFrame footer —
  totalMinRepayments?: string;
  totalExtraRepayments?: string;
  interestCharged?: string;
  principlePaidOff?: string;
}

export function PropertyCard({
  address,
  type,
  estimated,
  isLinkedToBank = false,
  borderless = false,
  loanAmount,
  equity,
  lvr,
  lvrPercent = 0,
  lenderName,
  interestRate,
  yearsRemaining,
  minRepayments,
  averageRepayments,
  redrawAmount,
  offsetAccount,
  totalMinRepayments,
  totalExtraRepayments,
  interestCharged,
  principlePaidOff,
}: PropertyCardProps) {
  const [expanded, setExpanded] = React.useState(false);

  return (
    <div
      className={cn(
        "overflow-hidden flex flex-col",
        !borderless && "border border-border",
      )}
    >
      {/* Header row */}
      {isLinkedToBank ? (
        <Button
          type="button"
          variant="ghost"
          aria-expanded={expanded}
          onClick={() => setExpanded((prev) => !prev)}
          className="h-auto w-full justify-start gap-1.5 px-5 py-3 text-left has-[>svg]:px-5"
        >
          <span className="flex-1 min-w-0 truncate text-label-medium text-foreground">
            {address}
          </span>
          {type && (
            <Badge className="shrink-0" variant="outline">
              {type}
            </Badge>
          )}
          <ChevronDown
            className={cn(
              "h-5 w-5 shrink-0 text-muted-foreground transition-transform duration-200",
              expanded && "rotate-180",
            )}
          />
        </Button>
      ) : (
        <div className="flex items-center gap-1.5 px-5 py-3">
          <span className="text-label-medium text-foreground">{address}</span>
          {type && <Badge variant="outline">{type}</Badge>}
        </div>
      )}

      {!isLinkedToBank && (
        <p className="px-5 pb-2 text-xs italic text-muted-foreground">
          No mortgage account linked to this property
        </p>
      )}

      {/* Static fields — always visible */}
      <div
        className={cn(
          "grid gap-5 px-5 py-[15px]",
          isLinkedToBank ? "grid-cols-2" : "grid-cols-1",
        )}
      >
        <FinancialDetailField label="Estimated Value" value={estimated} />
        {isLinkedToBank && (
          <>
            <FinancialDetailField label="Loan Amount" value={loanAmount} />
            <div className="col-span-2">
              <FinancialDetailField label="Equity" value={equity} />
            </div>
          </>
        )}
      </div>

      {isLinkedToBank && (
        <div className="px-5 pb-[15px]">
          <FinancialLvrBar
            percent={lvrPercent}
            label={lvr ?? `${lvrPercent}%`}
          />
        </div>
      )}

      {/* Expandable loan detail — CSS grid transition for smooth open/close */}
      {isLinkedToBank && (
        <div
          className={cn(
            "grid transition-[grid-template-rows] duration-200 ease-in-out",
            expanded ? "grid-rows-[1fr]" : "grid-rows-[0fr]",
          )}
        >
          <div className="overflow-hidden">
            <div className="flex flex-col gap-5 border-t border-border px-5 py-[15px]">
              <FinancialSubsectionTitle>Loan</FinancialSubsectionTitle>
              <div className="grid grid-cols-4 gap-x-4 gap-y-4">
                <FinancialDetailField
                  label="Name of Lender"
                  value={lenderName}
                />
                <FinancialDetailField
                  label="Current Loan Amount"
                  value={loanAmount}
                />
                <FinancialDetailField
                  label="Interest Rate"
                  value={interestRate}
                />
                <FinancialDetailField
                  label="Years Remaining"
                  value={yearsRemaining}
                />
              </div>
              <div className="grid grid-cols-4 gap-x-4 gap-y-4">
                <FinancialDetailField
                  label="Min Repayments"
                  value={minRepayments}
                />
                <FinancialDetailField
                  label="Average Repayments"
                  value={averageRepayments}
                />
                <FinancialDetailField
                  label="Redraw Amount"
                  value={redrawAmount}
                />
                <FinancialDetailField
                  label="Offset Account"
                  value={offsetAccount}
                />
              </div>
            </div>
            <FinancialSubtotalFrame>
              <div className="grid grid-cols-4 gap-x-4 gap-y-1">
                <FinancialDetailField
                  variant="footer"
                  label="Total Min Repayments"
                  value={totalMinRepayments}
                />
                <FinancialDetailField
                  variant="footer"
                  label="Total Extra Repayments"
                  value={totalExtraRepayments}
                />
                <FinancialDetailField
                  variant="footer"
                  label="Interest Charge"
                  value={interestCharged}
                />
                <FinancialDetailField
                  variant="footer"
                  label="Principle Paid Off"
                  value={principlePaidOff}
                />
              </div>
            </FinancialSubtotalFrame>
          </div>
        </div>
      )}
    </div>
  );
}

// ---------------------------------------------------------------------------
// DebtCard
// ---------------------------------------------------------------------------

export interface DebtCardProps {
  // — Header row —
  lenderName?: string;
  currentLoanAmount?: string;
  /** Current annual interest rate e.g. `"6.04% p.a."` */
  interestRate?: string;
  // — Loan Stats section —
  originalLoanAmount?: string;
  /** Original term at drawdown e.g. `"30 years"` */
  originalLoanTerm?: string;
  /** Minimum scheduled monthly repayment */
  monthlyRepayments?: string;
  /** Available redraw balance */
  redrawAmount?: string;
  /** Linked offset account balance */
  offsetAmount?: string;
  /** Additional voluntary repayments per month */
  extraLoanRepayments?: string;
  // — SubtotalFrame footer —
  /** Cumulative repayments made within the selected date range */
  totalRepaymentsMade?: string;
  /** Cumulative interest paid within the selected date range */
  totalInterestPaid?: string;
  /** Remaining loan term e.g. `"25 years"` */
  yearsRemaining?: string;
}

export function DebtCard({
  lenderName,
  currentLoanAmount,
  interestRate,
  originalLoanAmount,
  originalLoanTerm,
  monthlyRepayments,
  redrawAmount,
  offsetAmount,
  extraLoanRepayments,
  totalRepaymentsMade,
  totalInterestPaid,
  yearsRemaining,
}: DebtCardProps) {
  return (
    <div className="border border-border overflow-hidden flex flex-col h-full">
      {/* Header row — fixed min-h so two cards in a grid row have aligned headers */}
      <div className="grid grid-cols-3 gap-5 px-5 py-[15px] border-b border-border min-h-[7rem] items-start">
        <FinancialDetailField label="Name of Lender" value={lenderName} />
        <FinancialDetailField
          label="Current Loan Amount"
          value={currentLoanAmount}
        />
        <FinancialDetailField
          label="Current Interest Rate"
          value={interestRate}
        />
      </div>

      {/* Loan Stats section */}
      <div className="px-5 py-[15px] flex flex-col gap-5 flex-1">
        <FinancialSubsectionTitle>Loan Stats</FinancialSubsectionTitle>
        <div className="grid grid-cols-3 gap-5">
          <FinancialDetailField
            label="Original Loan Amount"
            value={originalLoanAmount}
          />
          <FinancialDetailField
            label="Original Loan Term"
            value={originalLoanTerm}
          />
          <FinancialDetailField
            label="Monthly Repayments"
            value={monthlyRepayments}
          />
        </div>
        <div className="grid grid-cols-3 gap-5">
          <FinancialDetailField label="Redraw Amount" value={redrawAmount} />
          <FinancialDetailField label="Offset Account" value={offsetAmount} />
          <FinancialDetailField
            label="Extra Loan Repayments"
            value={extraLoanRepayments}
          />
        </div>
      </div>

      {/* Footer */}
      <FinancialSubtotalFrame>
        <div className="grid grid-cols-3 gap-x-4 gap-y-1">
          <FinancialDetailField
            variant="footer"
            label="Total Repayments Made"
            value={totalRepaymentsMade}
          />
          <FinancialDetailField
            variant="footer"
            label="Total Interest Paid"
            value={totalInterestPaid}
          />
          <FinancialDetailField
            variant="footer"
            label="Years Remaining"
            value={yearsRemaining}
          />
        </div>
      </FinancialSubtotalFrame>
    </div>
  );
}

// ---------------------------------------------------------------------------
// OtherLiabilityCard
// ---------------------------------------------------------------------------

export type OtherLiabilityType = "credit_card" | "personal_loan";

export interface OtherLiabilityCardProps {
  /**
   * Discriminates the field set and footer layout:
   * - `"credit_card"`   → Card Stats (Credit Limit, Min Payment, Annual Fee)
   * - `"personal_loan"` → Loan Stats (Original Amount, Term, Monthly Repayments)
   */
  type: OtherLiabilityType;
  lenderName?: string;
  /** Annual interest rate e.g. `"19.99% p.a."` */
  interestRate?: string;
  // ── Credit card fields ──
  /** Current outstanding balance on the card */
  currentBalance?: string;
  /** Approved credit limit */
  creditLimit?: string;
  /** Minimum required monthly payment */
  minMonthlyPayment?: string;
  annualFee?: string;
  /** Pre-computed available credit: `creditLimit − currentBalance` */
  availableCredit?: string;
  // ── Personal loan fields ──
  /** Current outstanding loan balance */
  currentLoanAmount?: string;
  originalLoanAmount?: string;
  /** Original term at drawdown e.g. `"5 years"` */
  originalLoanTerm?: string;
  /** Minimum scheduled monthly repayment */
  monthlyRepayments?: string;
  /** Remaining term e.g. `"2.5 years"` */
  currentLoanTermLeft?: string;
  // ── Shared footer ──
  /** Cumulative repayments made within the selected date range */
  totalRepaymentsMade?: string;
  /** Cumulative interest paid within the selected date range */
  totalInterestPaid?: string;
}

export function OtherLiabilityCard({
  type,
  lenderName,
  interestRate,
  currentBalance,
  creditLimit,
  minMonthlyPayment,
  annualFee,
  availableCredit,
  currentLoanAmount,
  originalLoanAmount,
  originalLoanTerm,
  monthlyRepayments,
  currentLoanTermLeft,
  totalRepaymentsMade,
  totalInterestPaid,
}: OtherLiabilityCardProps) {
  const isCreditCard = type === "credit_card";

  return (
    <div className="border border-border overflow-hidden flex flex-col h-full">
      {/* Header row — fixed min-h so two cards in a grid row have aligned headers */}
      <div className="grid grid-cols-3 gap-5 px-4 pt-5 pb-4 min-h-[7rem] items-start">
        <FinancialDetailField label="Lender" value={lenderName} />
        {isCreditCard ? (
          <FinancialDetailField
            label="Current Balance"
            value={currentBalance}
          />
        ) : (
          <FinancialDetailField
            label="Current Loan Amount"
            value={currentLoanAmount}
          />
        )}
        <FinancialDetailField label="Interest Rate" value={interestRate} />
      </div>

      {/* Stats section */}
      <div className="px-4 pt-4 pb-5 flex flex-col gap-5 border-t border-border flex-1">
        <FinancialSubsectionTitle>
          {isCreditCard ? "Card Stats" : "Loan Stats"}
        </FinancialSubsectionTitle>
        {isCreditCard ? (
          <div className="grid grid-cols-3 gap-5">
            <FinancialDetailField label="Credit Limit" value={creditLimit} />
            <FinancialDetailField
              label="Min Monthly Payment"
              value={minMonthlyPayment}
            />
            <FinancialDetailField label="Annual Fee" value={annualFee} />
          </div>
        ) : (
          <div className="grid grid-cols-3 gap-5">
            <FinancialDetailField
              label="Original Loan Amount"
              value={originalLoanAmount}
            />
            <FinancialDetailField
              label="Original Loan Term"
              value={originalLoanTerm}
            />
            <FinancialDetailField
              label="Monthly Repayments"
              value={monthlyRepayments}
            />
          </div>
        )}
      </div>

      {/* Footer */}
      <FinancialSubtotalFrame>
        {isCreditCard ? (
          <div className="grid grid-cols-2 gap-x-4 gap-y-1">
            <FinancialDetailField
              variant="footer"
              label="Total Interest Paid"
              value={totalInterestPaid}
            />
            <FinancialDetailField
              variant="footer"
              label="Available Credit"
              value={availableCredit}
            />
          </div>
        ) : (
          <div className="grid grid-cols-3 gap-x-4 gap-y-1">
            <FinancialDetailField
              variant="footer"
              label="Total Repayments Made"
              value={totalRepaymentsMade}
            />
            <FinancialDetailField
              variant="footer"
              label="Total Interest Paid"
              value={totalInterestPaid}
            />
            <FinancialDetailField
              variant="footer"
              label="Years Remaining"
              value={currentLoanTermLeft}
            />
          </div>
        )}
      </FinancialSubtotalFrame>
    </div>
  );
}

// ---------------------------------------------------------------------------
// AlertCard
// ---------------------------------------------------------------------------

export type AlertSeverity = "NEED_ACTION" | "WATCH" | "INSIGHT";
export type AlertActionType = "DISMISS" | "SNOOZE";

const SEVERITY_CLASSES: Record<AlertSeverity, { dot: string; border: string }> =
  {
    NEED_ACTION: { dot: "bg-destructive", border: "border-destructive" },
    WATCH: { dot: "bg-warning", border: "border-warning" },
    INSIGHT: { dot: "bg-success", border: "border-success" },
  };

export interface AlertCardProps {
  id: string;
  name: string;
  severityCode: AlertSeverity;
  /** Whether this alert has an active ignore period */
  ignored?: boolean;
  /** Human-readable date string e.g. "31/12/2025" */
  ignoredUntil?: string;
  /** Currently selected action, controlled externally */
  selectedAction?: AlertActionType | null;
  onActionChange?: (action: AlertActionType) => void;
}

export function AlertCard({
  id,
  name,
  severityCode,
  ignored = false,
  ignoredUntil,
  selectedAction = null,
  onActionChange,
}: AlertCardProps) {
  const { dot, border } = SEVERITY_CLASSES[severityCode];

  return (
    <div className={cn("flex flex-col gap-1.5 border p-2.5 px-3", border)}>
      {/* Alert name row */}
      <div className="flex items-center gap-1.5">
        <span className={cn("h-[9px] w-[9px] shrink-0 rounded-full", dot)} />
        <span
          className={cn(
            "text-sm font-medium leading-tight",
            ignored ? "text-muted-foreground line-through" : "text-foreground",
          )}
        >
          {name}
        </span>
      </div>

      {ignored ? (
        <span className="ml-[15px] text-xs italic text-muted-foreground/60">
          Ignored until {ignoredUntil}
        </span>
      ) : (
        <RadioGroup
          value={selectedAction ?? ""}
          onValueChange={(val) => onActionChange?.(val as AlertActionType)}
          className="ml-[15px] flex flex-col gap-1"
        >
          <div className="flex items-center gap-2">
            <RadioGroupItem value="DISMISS" id={`dismiss-${id}`} />
            <label
              htmlFor={`dismiss-${id}`}
              className="cursor-pointer select-none text-sm leading-none text-muted-foreground"
            >
              Mark as done (will reset in 6 months)
            </label>
          </div>
          <div className="flex items-center gap-2">
            <RadioGroupItem value="SNOOZE" id={`snooze-${id}`} />
            <label
              htmlFor={`snooze-${id}`}
              className="cursor-pointer select-none text-sm leading-none text-muted-foreground"
            >
              Snooze for 30 days
            </label>
          </div>
        </RadioGroup>
      )}
    </div>
  );
}

// ---------------------------------------------------------------------------
// AboutCard
// ---------------------------------------------------------------------------

export interface AboutCardProps {
  title?: string;
  firstName?: string;
  lastName?: string;
  phone?: string;
  email?: string;
  dob?: string;
  gender?: string;
  maritalStatus?: string;
  numDependants?: string;
  /** Individual dependant records — shows DOB + age for each. */
  dependants?: Array<{ dob: string }>;
  citizenStatus?: string;
  residentialAddress?: string;
  residentialStatus?: string;
  timeAtAddressYears?: string;
  timeAtAddressMonths?: string;
  driversLicence?: string;
  passport?: string;
  propertyInTrust?: string;
  companyOwnership?: string;
  /** Remove the outer card border. Use when the card is already inside a bordered container. */
  borderless?: boolean;
}

function ageFromDob(dobStr: string): number | null {
  if (!dobStr) return null;
  const dob = new Date(dobStr);
  if (isNaN(dob.getTime())) return null;
  const today = new Date();
  let age = today.getFullYear() - dob.getFullYear();
  const m = today.getMonth() - dob.getMonth();
  if (m < 0 || (m === 0 && today.getDate() < dob.getDate())) age--;
  return age >= 0 ? age : null;
}

/**
 * Display card for applicant personal / contact information.
 * Used inside the Summary tab applicant sub-tabs.
 */
export function AboutCard({
  title,
  firstName,
  lastName,
  phone,
  email,
  dob,
  gender,
  maritalStatus,
  numDependants,
  dependants,
  citizenStatus,
  residentialAddress,
  residentialStatus,
  timeAtAddressYears,
  timeAtAddressMonths,
  driversLicence,
  passport,
  propertyInTrust,
  companyOwnership,
  borderless = false,
}: AboutCardProps) {
  const fullName =
    [title, firstName, lastName].filter(Boolean).join(" ") || "—";

  const timeAtAddress =
    timeAtAddressYears || timeAtAddressMonths
      ? [
          timeAtAddressYears && `${timeAtAddressYears}yr`,
          timeAtAddressMonths && `${timeAtAddressMonths}mo`,
        ]
          .filter(Boolean)
          .join(" ")
      : undefined;

  return (
    <div
      className={cn(
        "overflow-hidden divide-y divide-border",
        !borderless && "border border-border",
      )}
    >
      {/* Identity — personal details + citizenship documents */}
      <div className="grid grid-cols-4 gap-x-6 gap-y-4 px-5 py-4">
        <FinancialDetailField label="Full Name" value={fullName} />
        <FinancialDetailField label="Date of Birth" value={dob || "—"} />
        <FinancialDetailField label="Gender" value={gender || "—"} />
        <FinancialDetailField
          label="Citizenship"
          value={citizenStatus || "—"}
        />
        <FinancialDetailField
          label="Driver's Licence"
          value={driversLicence || "—"}
        />
        <FinancialDetailField label="Passport" value={passport || "—"} />
      </div>

      {/* Contact */}
      <div className="grid grid-cols-4 gap-x-6 gap-y-4 px-5 py-4">
        <FinancialDetailField label="Phone" value={phone || "—"} />
        <FinancialDetailField label="Email" value={email || "—"} />
      </div>

      {/* Family — marital status + dependants as a dedicated section */}
      <div className="grid grid-cols-4 gap-x-6 gap-y-4 px-5 py-4">
        <FinancialDetailField
          label="Marital Status"
          value={maritalStatus || "—"}
        />
        <FinancialDetailField
          label="No. of Dependants"
          value={numDependants ?? "—"}
        />
        {dependants &&
          dependants.map((dep, i) => {
            const age = ageFromDob(dep.dob);
            const dobFormatted = formatDateShort(dep.dob) || "—";
            const value =
              age !== null ? `${dobFormatted} · age ${age}` : dobFormatted;
            return (
              <FinancialDetailField
                key={i}
                label={`Dependant ${i + 1}`}
                value={value}
              />
            );
          })}
      </div>

      {/* Residence */}
      <div className="grid grid-cols-4 gap-x-6 gap-y-4 px-5 py-4">
        <div className="col-span-2">
          <FinancialDetailField
            label="Residential Address"
            value={residentialAddress || "—"}
          />
        </div>
        <FinancialDetailField
          label="Residential Status"
          value={residentialStatus || "—"}
        />
        {timeAtAddress && (
          <FinancialDetailField label="Time at Address" value={timeAtAddress} />
        )}
      </div>

      {/* Ownership */}
      <div className="grid grid-cols-4 gap-x-6 gap-y-4 px-5 py-4">
        <FinancialDetailField
          label="Property in Trust"
          value={propertyInTrust || "—"}
        />
        <FinancialDetailField
          label="Company Ownership"
          value={companyOwnership || "—"}
        />
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// IncomeCard
// ---------------------------------------------------------------------------

export interface IncomeCardItem {
  incomeType: string;
  jobTitle?: string;
  companyName?: string;
  companyAddress?: string;
  startDate?: string;
  stillInPosition?: boolean;
  endDate?: string;
  companyType?: string;
  /** Pre-formatted amount + frequency e.g. "$9,500 / Monthly" */
  amountLabel: string;
}

export interface IncomeCardProps {
  items: IncomeCardItem[];
  /** Pre-formatted total monthly income e.g. "$12,300" */
  totalMonthly?: string;
  /** Remove the outer card border. Use when the card is already inside a bordered container. */
  borderless?: boolean;
}

/**
 * Display card for applicant income items.
 * Each income source is an accordion row: collapsed = type + amount,
 * expanded = full employment details.
 */
export function IncomeCard({
  items,
  totalMonthly,
  borderless = false,
}: IncomeCardProps) {
  if (items.length === 0) {
    return (
      <div className={cn("px-5 py-4", !borderless && "border border-border")}>
        <p className="text-sm text-muted-foreground">No income recorded.</p>
      </div>
    );
  }

  return (
    <div
      className={cn(
        "overflow-hidden flex flex-col",
        !borderless && "border border-border",
      )}
    >
      <Accordion multiple>
        {items.map((item, i) => (
          <AccordionItem key={i} value={String(i)}>
            <AccordionTrigger className="px-5">
              <div className="flex flex-1 items-center justify-between pr-2">
                <div className="flex items-center gap-2">
                  <span className="text-label-medium text-foreground">
                    {item.incomeType}
                  </span>
                  {item.jobTitle && (
                    <span className="text-body-small text-muted-foreground">
                      · {item.jobTitle}
                    </span>
                  )}
                </div>
                <span className="text-label-medium text-foreground">
                  {item.amountLabel}
                </span>
              </div>
            </AccordionTrigger>
            <AccordionContent className="px-5">
              <div className="grid grid-cols-3 gap-x-6 gap-y-4 pb-2 pt-1">
                <FinancialDetailField
                  label="Job Title"
                  value={item.jobTitle || "—"}
                />
                <FinancialDetailField
                  label="Company"
                  value={item.companyName || "—"}
                />
                <FinancialDetailField
                  label="Start Date"
                  value={formatDateShort(item.startDate)}
                />
                <FinancialDetailField
                  label="Status"
                  value={
                    item.stillInPosition === undefined
                      ? "—"
                      : item.stillInPosition
                        ? "Still in position"
                        : item.endDate
                          ? `Ended ${formatDateShort(item.endDate)}`
                          : "No longer in position"
                  }
                />
                {item.companyAddress && (
                  <FinancialDetailField
                    label="Company Address"
                    value={item.companyAddress}
                  />
                )}
              </div>
            </AccordionContent>
          </AccordionItem>
        ))}
      </Accordion>
      {totalMonthly && (
        <FinancialSubtotalFrame>
          <FinancialSubtotalBlock
            monthlyAverage={totalMonthly}
            label="Total Monthly Income"
          />
        </FinancialSubtotalFrame>
      )}
    </div>
  );
}

// ---------------------------------------------------------------------------
// ExpensesCard
// ---------------------------------------------------------------------------

const EXPENSE_ICON_MAP: Record<string, LucideIcon> = {
  groceries: ShoppingCart,
  "dining out": UtensilsCrossed,
  dining: UtensilsCrossed,
  restaurants: UtensilsCrossed,
  transport: Car,
  transportation: Car,
  vehicle: Car,
  utilities: Zap,
  electricity: Zap,
  insurance: Shield,
  "council rates": Landmark,
  council: Landmark,
  rates: Landmark,
  medical: HeartPulse,
  health: HeartPulse,
  subscriptions: RefreshCw,
  subscription: RefreshCw,
  "credit card": CreditCard,
  education: GraduationCap,
  childcare: Baby,
  entertainment: Tv,
  gym: Dumbbell,
  fitness: Dumbbell,
  clothing: Shirt,
  rent: Building2,
};

function getExpenseIcon(expenseType: string): LucideIcon {
  return EXPENSE_ICON_MAP[expenseType.toLowerCase()] ?? Receipt;
}

export interface ExpensesCardItem {
  expenseType: string;
  /** Pre-formatted amount + frequency e.g. "$800 / Monthly" */
  amountLabel: string;
}

export interface ExpensesCardProps {
  items: ExpensesCardItem[];
  /** Pre-formatted total monthly expenses e.g. "$2,100" */
  totalMonthly?: string;
  /** Remove the outer card border. Use when the card is already inside a bordered container. */
  borderless?: boolean;
}

/**
 * Display card for applicant expense items.
 * Each expense renders as an icon-labelled row with a destructive amount value.
 */
export function ExpensesCard({
  items,
  totalMonthly,
  borderless = false,
}: ExpensesCardProps) {
  if (items.length === 0) {
    return (
      <div className={cn("px-5 py-4", !borderless && "border border-border")}>
        <p className="text-sm text-muted-foreground">No expenses recorded.</p>
      </div>
    );
  }

  return (
    <div
      className={cn(
        "overflow-hidden flex flex-col",
        !borderless && "border border-border",
      )}
    >
      <div className="flex flex-col">
        {items.map((item, i) => {
          const Icon = getExpenseIcon(item.expenseType);
          return (
            <div
              key={item.expenseType}
              className={cn(
                "flex items-center justify-between gap-4 px-5 py-2.5",
                i < items.length - 1 && "border-b border-border",
              )}
            >
              <div className="flex items-center gap-2.5">
                <Icon className="size-3.5 shrink-0 text-muted-foreground" />
                <span className="text-body-small text-foreground">
                  {item.expenseType}
                </span>
              </div>
              <span className="text-label-medium whitespace-nowrap text-destructive">
                {item.amountLabel}
              </span>
            </div>
          );
        })}
      </div>
      {totalMonthly && (
        <FinancialSubtotalFrame>
          <FinancialSubtotalBlock
            monthlyAverage={totalMonthly}
            label="Total Monthly Expenses"
          />
        </FinancialSubtotalFrame>
      )}
    </div>
  );
}
