import { Building2 } from "lucide-react";
import { cn } from "@/lib/utils";
import { Badge } from "@/components/ui/badge";
import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "@/components/ui/accordion";
import { formatCurrency } from "@/lib/format-currency";

// ─── Types ────────────────────────────────────────────────────────────────────

export type PropertyMortgage = {
  id: string;
  /** Display label e.g. "Mortgage" */
  label: string;
  /** Loan type shown as a badge e.g. "Home Loan", "Investment Loan" */
  type: string;
  /** Monthly repayment shown in the accordion header */
  monthlyRepayment: number;
  /** Outstanding loan balance */
  loanAmount: number;
  /** Monthly repayment shown in Loan Details */
  repaymentAmount: number;
  /** Annual interest rate (%) */
  interestRate: number;
};

export type PropertyAssetCardProps = {
  /** Full property address */
  address: string;
  /** Asset category label shown below the address */
  assetType?: string;
  /** URL for the lending institution's logo — falls back to a building icon */
  institutionLogoUrl?: string;
  /** Current estimated market value */
  estimatedValue: number;
  /** Loan-to-value ratio (0–100) */
  lvr?: number;
  /** Net equity in dollars (estimatedValue − totalOwing) */
  netEquity?: number;
  /** Linked mortgage records */
  mortgages?: PropertyMortgage[];
  className?: string;
};

// ─── Constants ────────────────────────────────────────────────────────────────

const EMPTY_MORTGAGES: PropertyMortgage[] = [];

// ─── Component ────────────────────────────────────────────────────────────────

/**
 * PropertyAssetCard — summary card for a single property asset in the loan
 * wizard Assets tab.
 *
 * Shows: institution logo, address, estimated value, interest rate + LVR stats,
 * net equity highlight, and an expandable mortgage accordion with Loan Details
 * and Property Statistics sub-sections.
 *
 * Figma: WealthX-Backoffice---Mobile-App — node 17418:41358
 */
export function PropertyAssetCard({
  address,
  assetType = "Property",
  institutionLogoUrl,
  estimatedValue,
  lvr,
  netEquity,
  mortgages = EMPTY_MORTGAGES,
  className,
}: PropertyAssetCardProps) {
  const primaryRate = mortgages[0]?.interestRate;

  return (
    <div
      className={cn(
        "flex flex-col gap-4 border border-border p-4 font-sans",
        className,
      )}
    >
      <div className="flex items-start gap-3">
        <div className="flex size-14 shrink-0 items-center justify-center bg-muted">
          {institutionLogoUrl ? (
            <img
              src={institutionLogoUrl}
              alt=""
              className="size-full object-contain"
            />
          ) : (
            <Building2
              className="size-6 text-muted-foreground"
              aria-hidden="true"
            />
          )}
        </div>

        <div className="flex min-w-0 flex-1 items-start justify-between gap-2">
          <div className="flex min-w-0 flex-col gap-0.5">
            <span className="text-body-small font-semibold text-foreground">
              {address}
            </span>
            <span className="text-body-small text-muted-foreground">
              {assetType}
            </span>
          </div>
          <span className="shrink-0 text-body-small font-semibold text-foreground">
            {formatCurrency(estimatedValue)}
          </span>
        </div>
      </div>

      {(primaryRate != null || lvr != null) && (
        <div className="flex gap-6 text-xs">
          {primaryRate != null && (
            <span className="text-muted-foreground">
              Interest Rate:{" "}
              <span className="font-semibold text-foreground">
                {primaryRate}%
              </span>
            </span>
          )}
          {lvr != null && (
            <span className="text-muted-foreground">
              LVR <span className="font-semibold text-foreground">{lvr}%</span>
            </span>
          )}
        </div>
      )}

      <div className="border-t border-border" />

      {netEquity != null && (
        <div className="flex items-center justify-between border border-primary/40 bg-primary/10 px-4 py-3">
          <span className="text-body-small font-semibold text-foreground">
            Net Equity
          </span>
          <span className="text-body-small font-semibold text-foreground">
            {formatCurrency(netEquity)}
          </span>
        </div>
      )}

      {mortgages.length > 0 && (
        <Accordion multiple>
          {mortgages.map((mortgage) => (
            <AccordionItem key={mortgage.id} value={mortgage.id}>
              <AccordionTrigger>
                <div className="flex flex-1 items-center justify-between pr-2">
                  <div className="flex flex-col gap-1.5 items-start">
                    <span className="text-body-small font-semibold text-foreground">
                      {mortgage.label}
                    </span>
                    <Badge variant="secondary">{mortgage.type}</Badge>
                  </div>
                  <span className="text-body-small font-semibold text-foreground">
                    {formatCurrency(mortgage.monthlyRepayment)}
                  </span>
                </div>
              </AccordionTrigger>

              <AccordionContent>
                <div className="flex flex-col gap-2 pt-1">
                  <div className="flex flex-col gap-2 bg-muted/50 p-4">
                    <span className="text-body-small font-semibold text-foreground">
                      Loan Details
                    </span>
                    <DetailRow
                      label="Loan Amount"
                      value={formatCurrency(mortgage.loanAmount)}
                    />
                    <DetailRow
                      label="Repayment Amount"
                      value={formatCurrency(mortgage.repaymentAmount)}
                    />
                    <DetailRow
                      label="Interest Rate"
                      value={`${mortgage.interestRate}%`}
                    />
                  </div>

                  <div className="flex flex-col gap-2 border border-primary/40 bg-primary/10 p-4">
                    <span className="text-body-small font-semibold text-foreground">
                      Property Statistics
                    </span>
                    <DetailRow
                      label="Property Estimate"
                      value={formatCurrency(estimatedValue)}
                    />
                    {lvr != null && <DetailRow label="LVR" value={`${lvr}%`} />}
                    {netEquity != null && (
                      <>
                        <div className="border-t border-primary/40" />
                        <DetailRow
                          label="Equity Available"
                          value={formatCurrency(netEquity)}
                        />
                      </>
                    )}
                  </div>
                </div>
              </AccordionContent>
            </AccordionItem>
          ))}
        </Accordion>
      )}
    </div>
  );
}

// ─── Internal helpers ─────────────────────────────────────────────────────────

function DetailRow({ label, value }: { label: string; value: string }) {
  return (
    <div className="flex items-center justify-between">
      <span className="text-xs text-muted-foreground">{label}</span>
      <span className="text-xs font-semibold text-foreground">{value}</span>
    </div>
  );
}
