import * as React from "react";
import { Check } from "lucide-react";
import { cn } from "@/lib/utils";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  LoanOptionGroup,
  type LoanOptionItem,
} from "@/components/ui/loan-option-group";
import { MoneyInputWithSlider } from "@/components/ui/money-input-with-slider";
import {
  Combobox,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxInput,
  ComboboxItem,
  ComboboxList,
  ComboboxTrigger,
  ComboboxValue,
} from "@/components/ui/combobox";
import { YES_NO_OPTIONS as YES_NO } from "@/lib/loan-constants";

// ─── Shared option constants ────────────────────────────────────────────────

function scaleOptions(min: number, max: number): LoanOptionItem[] {
  return Array.from({ length: max - min + 1 }, (_, i) => {
    const v = String(min + i);
    return { value: v, label: v };
  });
}

/** 1–10 scale reused by the fixed-rate and rate-rise concern steps. */
const SCALE_1_10: LoanOptionItem[] = scaleOptions(1, 10);

// ─── 1. LoanPurposeStep ──────────────────────────────────────────────────────

export const LENDING_TYPE_OPTIONS: LoanOptionItem[] = [
  { value: "owner-occupier", label: "Owner Occupier" },
  { value: "investment", label: "Investment" },
  { value: "both", label: "Both" },
];

export const LOAN_PURPOSE_OPTIONS: LoanOptionItem[] = [
  { value: "buy", label: "Buy a New Property" },
  { value: "refinance", label: "Refinance" },
  { value: "equity", label: "Equity Release" },
  { value: "construction", label: "Construction" },
];

export type LoanPurposeStepProps = {
  lendingType: string | null;
  loanPurpose: string | null;
  onLendingTypeChange: (v: string) => void;
  onLoanPurposeChange: (v: string) => void;
  className?: string;
};

export function LoanPurposeStep({
  lendingType,
  loanPurpose,
  onLendingTypeChange,
  onLoanPurposeChange,
  className,
}: LoanPurposeStepProps) {
  // No in-content nav here — the wizard shell owns the bottom Prev/Next controls.
  return (
    <div className={cn("flex flex-col gap-10 font-sans", className)}>
      <LoanOptionGroup
        title="What Type of Lending Are You Looking For?"
        options={LENDING_TYPE_OPTIONS}
        value={lendingType ?? undefined}
        onChange={(v) => onLendingTypeChange(v as string)}
      />
      <LoanOptionGroup
        title="What Would You Like to Do?"
        options={LOAN_PURPOSE_OPTIONS}
        value={loanPurpose ?? undefined}
        onChange={(v) => onLoanPurposeChange(v as string)}
      />
    </div>
  );
}

// ─── 2. LoanDetailsBuyStep ───────────────────────────────────────────────────

// Slider ranges for the Buy-a-property value inputs (whole dollars).
const PROPERTY_VALUE_MIN = 100_000;
const PROPERTY_VALUE_MAX = 3_000_000;
const LOAN_AMOUNT_MIN = 50_000;
const LOAN_AMOUNT_MAX = 2_500_000;
const VALUE_SLIDER_STEP = 10_000;

export type LoanDetailsBuyStepProps = {
  isPropertyKnown: string | null;
  propertyAddress?: string;
  propertyEstimate?: number;
  loanAmount?: number;
  /** Address suggestions for the autocomplete search (e.g. from a places API). */
  addressOptions?: string[];
  onIsPropertyKnownChange: (v: string) => void;
  onPropertyAddressChange: (v: string) => void;
  onPropertyEstimateChange: (v: number) => void;
  onLoanAmountChange: (v: number) => void;
  className?: string;
};

export function LoanDetailsBuyStep({
  isPropertyKnown,
  propertyAddress = "",
  propertyEstimate = 0,
  loanAmount = 0,
  addressOptions = [],
  onIsPropertyKnownChange,
  onPropertyAddressChange,
  onPropertyEstimateChange,
  onLoanAmountChange,
  className,
}: LoanDetailsBuyStepProps) {
  return (
    <div className={cn("flex flex-col gap-8 font-sans", className)}>
      <LoanOptionGroup
        title="Do you have a specific property in mind?"
        options={YES_NO}
        value={isPropertyKnown ?? undefined}
        onChange={(v) => onIsPropertyKnownChange(v as string)}
      />

      {isPropertyKnown === "yes" && (
        <div className="flex flex-col gap-6">
          <div className="flex flex-col gap-1.5">
            <Label htmlFor="propertyAddress">Property Address</Label>
            <Combobox
              items={addressOptions}
              value={propertyAddress || null}
              onValueChange={(val) =>
                onPropertyAddressChange((val as string | null) ?? "")
              }
            >
              <ComboboxTrigger
                id="propertyAddress"
                aria-label="Property address"
                className="w-full"
              >
                <ComboboxValue placeholder="Enter property address" />
              </ComboboxTrigger>
              <ComboboxContent>
                <ComboboxInput placeholder="Search address..." />
                <ComboboxList>
                  {(item: string) => (
                    <ComboboxItem key={item} value={item}>
                      {item}
                    </ComboboxItem>
                  )}
                </ComboboxList>
                <ComboboxEmpty>No matching address.</ComboboxEmpty>
              </ComboboxContent>
            </Combobox>
          </div>

          <MoneyInputWithSlider
            label="Property Value"
            value={propertyEstimate}
            min={PROPERTY_VALUE_MIN}
            max={PROPERTY_VALUE_MAX}
            step={VALUE_SLIDER_STEP}
            onChange={onPropertyEstimateChange}
          />
          <MoneyInputWithSlider
            label="Loan Amount"
            value={loanAmount}
            min={LOAN_AMOUNT_MIN}
            max={LOAN_AMOUNT_MAX}
            step={VALUE_SLIDER_STEP}
            onChange={onLoanAmountChange}
          />
        </div>
      )}
    </div>
  );
}

// ─── 3. LoanDetailsRefinanceStep ─────────────────────────────────────────────

export type RefinanceProperty = {
  id: string;
  address: string;
  estimateValue?: number;
};

export type LoanDetailsRefinanceStepProps = {
  properties: RefinanceProperty[];
  selectedIds: string[];
  onToggle: (id: string) => void;
  className?: string;
};

export function LoanDetailsRefinanceStep({
  properties,
  selectedIds,
  onToggle,
  className,
}: LoanDetailsRefinanceStepProps) {
  const selectedSet = new Set(selectedIds);

  return (
    <div className={cn("flex flex-col gap-6 font-sans", className)}>
      <p className="text-label-medium text-foreground">
        Select What Properties You Would Like to Refinance
      </p>

      {properties.length === 0 ? (
        <p className="text-body-small text-muted-foreground">
          No properties found. Add properties in the Assets section first.
        </p>
      ) : (
        <div className="flex flex-col gap-3">
          {properties.map((prop) => (
            <button
              key={prop.id}
              type="button"
              onClick={() => onToggle(prop.id)}
              className={cn(
                "flex items-center justify-between border p-4 text-left transition-colors",
                selectedSet.has(prop.id)
                  ? "border-primary bg-primary/5"
                  : "border-border bg-background hover:bg-accent",
              )}
            >
              <div className="flex flex-col gap-0.5">
                <span className="text-label-medium text-foreground">
                  {prop.address}
                </span>
                {prop.estimateValue != null && (
                  <span className="text-caption text-muted-foreground">
                    Est. ${prop.estimateValue.toLocaleString("en-AU")}
                  </span>
                )}
              </div>
              <SelectionCheckIndicator
                checked={selectedSet.has(prop.id)}
                className="size-5 shrink-0"
              />
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

// ─── 4. LoanFixedRateConcernStep ─────────────────────────────────────────────

export type LoanFixedRateConcernStepProps = {
  fixedRateConcern: string | null;
  jobSecurityScale: string | null;
  onFixedRateConcernChange: (v: string) => void;
  onJobSecurityScaleChange: (v: string) => void;
  className?: string;
};

export function LoanFixedRateConcernStep({
  fixedRateConcern,
  jobSecurityScale,
  onFixedRateConcernChange,
  onJobSecurityScaleChange,
  className,
}: LoanFixedRateConcernStepProps) {
  return (
    <div className={cn("flex flex-col gap-10 font-sans", className)}>
      <LoanOptionGroup
        title="Would you consider taking a fixed rate (either all fixed or a split loan with part fixed and part variable)?"
        options={YES_NO}
        value={fixedRateConcern ?? undefined}
        onChange={(v) => onFixedRateConcernChange(v as string)}
      />
      {fixedRateConcern && (
        <LoanOptionGroup
          title="On a scale of 1–10 how would you rate your current job security? (1 = not secure, 10 = highly secure)"
          options={SCALE_1_10}
          value={jobSecurityScale ?? undefined}
          onChange={(v) => onJobSecurityScaleChange(v as string)}
        />
      )}
    </div>
  );
}

// ─── 5. LoanBorrowIntendStep ─────────────────────────────────────────────────

export type LoanBorrowIntendStepProps = {
  borrowIntend: string | null;
  onBorrowIntendChange: (v: string) => void;
  className?: string;
};

export function LoanBorrowIntendStep({
  borrowIntend,
  onBorrowIntendChange,
  className,
}: LoanBorrowIntendStepProps) {
  return (
    <div className={cn("flex flex-col gap-10 font-sans", className)}>
      <LoanOptionGroup
        title="Do you intend to borrow money other than your property?"
        options={YES_NO}
        value={borrowIntend ?? undefined}
        onChange={(v) => onBorrowIntendChange(v as string)}
      />
    </div>
  );
}

// ─── 6. LoanPriorityStep ─────────────────────────────────────────────────────

export const LOAN_PRIORITY_OPTIONS: LoanOptionItem[] = [
  { value: "lowest-rate", label: "Lowest Rate" },
  { value: "offset-account", label: "Offset Account" },
  { value: "redraw-facility", label: "Redraw Facility" },
  { value: "repayment-flexibility", label: "Repayment Flexibility" },
  { value: "lender-stability", label: "Lender Stability" },
  { value: "customer-service", label: "Customer Service" },
];

export type LoanPriorityStepProps = {
  priorities: string[];
  onPrioritiesChange: (v: string[]) => void;
  className?: string;
};

export function LoanPriorityStep({
  priorities,
  onPrioritiesChange,
  className,
}: LoanPriorityStepProps) {
  return (
    <div className={cn("flex flex-col gap-10 font-sans", className)}>
      <LoanOptionGroup
        title="List out your top three priorities with the loan"
        options={LOAN_PRIORITY_OPTIONS}
        values={priorities}
        multiple
        max={3}
        showRank
        onChange={(v) => onPrioritiesChange(v as string[])}
      />
    </div>
  );
}

// ─── 7. LoanRetirementPlanStep ───────────────────────────────────────────────

export type LoanRetirementPlanStepProps = {
  retirementAge: number;
  hasRetirementPlan: string | null;
  retirementAgeError?: string;
  onRetirementAgeChange: (v: number) => void;
  onHasRetirementPlanChange: (v: string) => void;
  className?: string;
};

export function LoanRetirementPlanStep({
  retirementAge,
  hasRetirementPlan,
  retirementAgeError,
  onRetirementAgeChange,
  onHasRetirementPlanChange,
  className,
}: LoanRetirementPlanStepProps) {
  return (
    <div className={cn("flex flex-col gap-10 font-sans", className)}>
      <div className="flex flex-col gap-1.5">
        <Label htmlFor="retirementAge">
          What age are you planning to retire?
        </Label>
        <Input
          id="retirementAge"
          type="number"
          min={0}
          max={100}
          value={retirementAge || ""}
          onChange={(e) => onRetirementAgeChange(Number(e.target.value))}
          placeholder="e.g. 65"
          aria-invalid={Boolean(retirementAgeError)}
          className="w-32"
        />
        {retirementAgeError && (
          <p className="text-caption text-destructive">{retirementAgeError}</p>
        )}
      </div>

      <LoanOptionGroup
        title="Do you plan or anticipate changes (other than retirement) to your future financial circumstances that could adversely impact your ability to repay the loan?"
        options={YES_NO}
        value={hasRetirementPlan ?? undefined}
        onChange={(v) => onHasRetirementPlanChange(v as string)}
      />
    </div>
  );
}

// ─── 8. LoanInterestRateRaiseConcernStep ─────────────────────────────────────

export type LoanInterestRateRaiseConcernStepProps = {
  raiseConcern: string | null;
  raiseConcernScale: string | null;
  onRaiseConcernChange: (v: string) => void;
  onRaiseConcernScaleChange: (v: string) => void;
  className?: string;
};

export function LoanInterestRateRaiseConcernStep({
  raiseConcern,
  raiseConcernScale,
  onRaiseConcernChange,
  onRaiseConcernScaleChange,
  className,
}: LoanInterestRateRaiseConcernStepProps) {
  return (
    <div className={cn("flex flex-col gap-10 font-sans", className)}>
      <LoanOptionGroup
        title="Are you concerned about rising interest rates?"
        options={YES_NO}
        value={raiseConcern ?? undefined}
        onChange={(v) => onRaiseConcernChange(v as string)}
      />
      {raiseConcern === "yes" && (
        <LoanOptionGroup
          title="On a scale of 1–10 how concerned are you about rising interest rates? (1 = not concerned, 10 = highly concerned)"
          options={SCALE_1_10}
          value={raiseConcernScale ?? undefined}
          onChange={(v) => onRaiseConcernScaleChange(v as string)}
        />
      )}
    </div>
  );
}

// ─── 9. LoanFeaturesStep ─────────────────────────────────────────────────────

export const LOAN_FEATURE_OPTIONS: LoanOptionItem[] = [
  { value: "offset", label: "Offset Account" },
  { value: "redraw", label: "Redraw" },
  { value: "split", label: "Split Loan" },
  { value: "extra-repayments", label: "Extra Repayments" },
  { value: "interest-only", label: "Interest Only" },
];

export type LoanFeaturesStepProps = {
  featuresAcknowledge: string | null;
  feature: string | null;
  onFeaturesAcknowledgeChange: (v: string) => void;
  onFeatureChange: (v: string) => void;
  className?: string;
};

export function LoanFeaturesStep({
  featuresAcknowledge,
  feature,
  onFeaturesAcknowledgeChange,
  onFeatureChange,
  className,
}: LoanFeaturesStepProps) {
  return (
    <div className={cn("flex flex-col gap-10 font-sans", className)}>
      <LoanOptionGroup
        title="Do you know what loan features you want? (e.g. offset account, redraw)"
        options={YES_NO}
        value={featuresAcknowledge ?? undefined}
        onChange={(v) => onFeaturesAcknowledgeChange(v as string)}
      />
      {featuresAcknowledge === "yes" && (
        <LoanOptionGroup
          title="What features are important to you?"
          options={LOAN_FEATURE_OPTIONS}
          value={feature ?? undefined}
          onChange={(v) => onFeatureChange(v as string)}
        />
      )}
    </div>
  );
}

// ─── Icon helpers ────────────────────────────────────────────────────────────

/**
 * SelectionCheckIndicator — a purely decorative checkmark box matching the
 * shared Checkbox component's visual language (border-input / bg-primary),
 * used inside rows where the ROW itself (not the indicator) is the clickable
 * element. Not the real Checkbox component: nesting an interactive Checkbox
 * inside an already-clickable row would create invalid nested interactive
 * controls.
 */
function SelectionCheckIndicator({
  checked,
  className,
}: {
  checked: boolean;
  className?: string;
}) {
  return (
    <div
      aria-hidden="true"
      className={cn(
        "flex items-center justify-center border border-input transition-all",
        checked
          ? "border-primary bg-primary text-primary-foreground"
          : "text-transparent",
        className,
      )}
    >
      <Check className="size-3.5" />
    </div>
  );
}
