import * as React from "react";
import { cn } from "@/lib/utils";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { DatePicker } from "@/components/ui/date-picker";
import {
  LoanOptionGroup,
  type LoanOptionItem,
} from "@/components/ui/loan-option-group";

// ─── Option lists (mirror loan-application-constants.tsx) ─────────────────────

const TITLE_OPTIONS: LoanOptionItem[] = [
  { value: "Dr", label: "Dr" },
  { value: "Miss", label: "Miss" },
  { value: "Mrs", label: "Mrs" },
  { value: "Mr", label: "Mr" },
  { value: "Prof", label: "Prof" },
  { value: "Rev", label: "Rev" },
];

const GENDER_OPTIONS: LoanOptionItem[] = [
  { value: "M", label: "Male" },
  { value: "F", label: "Female" },
  { value: "PS", label: "Prefer not to say" },
];

const CITIZEN_STATUS_OPTIONS: LoanOptionItem[] = [
  { value: "australian-citizen", label: "Australian Citizen" },
  { value: "permanent-resident", label: "Permanent Resident" },
  { value: "non-citizen", label: "Non-Citizen" },
];

const APPLICANT_RELATIONSHIP_OPTIONS: LoanOptionItem[] = [
  { value: "Married", label: "Married" },
  { value: "DeFacto", label: "De Facto" },
  { value: "Friend", label: "Friend" },
  { value: "FamilyMember", label: "Family Member" },
];

const MARITAL_STATUS_OPTIONS: LoanOptionItem[] = [
  { value: "Single", label: "Single" },
  { value: "Married", label: "Married" },
  { value: "DeFacto", label: "De Facto" },
  { value: "Separated", label: "Separated" },
  { value: "Divorced", label: "Divorced" },
  { value: "Widowed", label: "Widowed" },
];

const YES_NO_OPTIONS: LoanOptionItem[] = [
  { value: "Yes", label: "Yes" },
  { value: "No", label: "No" },
];

const PROPERTY_OWNERSHIP_OPTIONS: LoanOptionItem[] = [
  { value: "trust", label: "Yes — via Trust" },
  { value: "company", label: "Yes — via Company" },
  { value: "no", label: "No" },
];

export const MAX_DEPENDANTS = 20;

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

export type AboutYouFormData = {
  title?: string;
  gender?: string;
  citizenStatus?: string;
  /** Only relevant for joint applications */
  applicantRelationship?: string;
  maritalStatus?: string;
  hasDependants?: "Yes" | "No";
  dependants?: number;
  dependantDobs?: (Date | null)[];
  /** Only relevant for joint applications where co-applicant is married/defacto */
  childrenShared?: "Yes" | "No";
  propertyOwnership?: "trust" | "company" | "no";
  trustOrCompanyName?: string;
  tradingAs?: string;
  dateCommenced?: string;
  numberOfDirectors?: number | null;
  numberOfEmployees?: number | null;
};

export type AboutYouFormProps = {
  /** Current form values */
  data: AboutYouFormData;
  /** Called on every field change */
  onChange: (data: AboutYouFormData) => void;
  /**
   * When provided, the Relationship field is shown with this label,
   * e.g. "Relationship with James Harbour"
   */
  coApplicantName?: string;
  /** Whether this form is for the main applicant (affects relationship field visibility) */
  isMainApplicant?: boolean;
  className?: string;
};

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

type FieldRowProps = {
  label: string;
  htmlFor?: string;
  children: React.ReactNode;
  className?: string;
};

function FieldRow({ label, htmlFor, children, className }: FieldRowProps) {
  return (
    <div className={cn("flex flex-col gap-1.5", className)}>
      <Label htmlFor={htmlFor}>{label}</Label>
      {children}
    </div>
  );
}

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

/**
 * AboutYouForm — applicant personal status form in the loan wizard.
 *
 * Matches the frontend's `YourDetailsPersonalStatusStep`.
 * Fields: Title · Gender · Citizen Status · (Relationship) ·
 *         Marital Status · Dependants · Property Ownership
 *
 * Uses `LoanOptionGroup` for all button-group selections and
 * `DatePicker` for dependant DOBs.
 *
 * Figma: WealthX-Backoffice---Mobile-App (loan wizard — About You tab)
 */
export function AboutYouForm({
  data,
  onChange,
  coApplicantName,
  isMainApplicant = true,
  className,
}: AboutYouFormProps) {
  const hasCoApplicant = Boolean(coApplicantName);

  const isRelationshipMarriedOrDefacto =
    data.applicantRelationship === "Married" ||
    data.applicantRelationship === "DeFacto";

  const isRelationshipFriendOrFamily =
    data.applicantRelationship === "Friend" ||
    data.applicantRelationship === "FamilyMember";

  const showMaritalStatus = !hasCoApplicant || isRelationshipFriendOrFamily;

  const showDependantsSection = !(
    !isMainApplicant &&
    isRelationshipMarriedOrDefacto &&
    data.childrenShared === "Yes"
  );

  const showPropertyDetails =
    data.propertyOwnership === "trust" || data.propertyOwnership === "company";

  function set<K extends keyof AboutYouFormData>(
    key: K,
    value: AboutYouFormData[K],
  ) {
    onChange({ ...data, [key]: value });
  }

  function handleHasDependantsChange(value: string) {
    if (value === "Yes") {
      onChange({
        ...data,
        hasDependants: "Yes",
        dependants: data.dependants ?? 1,
        dependantDobs: data.dependantDobs?.length ? data.dependantDobs : [null],
      });
    } else {
      onChange({
        ...data,
        hasDependants: "No",
        dependants: 0,
        dependantDobs: [],
        childrenShared: undefined,
      });
    }
  }

  function handleDependantsCountChange(count: number) {
    const current = data.dependantDobs ?? [];
    const dobs = Array.from({ length: count }, (_, i) => current[i] ?? null);
    onChange({ ...data, dependants: count, dependantDobs: dobs });
  }

  function handlePropertyOwnershipChange(value: string) {
    if (value === "no") {
      onChange({
        ...data,
        propertyOwnership: "no",
        trustOrCompanyName: "",
        tradingAs: "",
        dateCommenced: "",
        numberOfDirectors: null,
        numberOfEmployees: null,
      });
    } else {
      set("propertyOwnership", value as "trust" | "company");
    }
  }

  function handleDependantDobChange(index: number, date: Date | undefined) {
    const dobs = [...(data.dependantDobs ?? [])];
    dobs[index] = date ?? null;
    set("dependantDobs", dobs);
  }

  return (
    <div className={cn("flex flex-col gap-8 font-sans", className)}>
      <LoanOptionGroup
        title="Title"
        options={TITLE_OPTIONS}
        value={data.title ?? ""}
        onChange={(v) => set("title", v as string)}
      />

      <LoanOptionGroup
        title="Gender"
        options={GENDER_OPTIONS}
        value={data.gender ?? ""}
        onChange={(v) => set("gender", v as string)}
      />

      <LoanOptionGroup
        title="Citizen Status"
        options={CITIZEN_STATUS_OPTIONS}
        value={data.citizenStatus ?? ""}
        onChange={(v) => set("citizenStatus", v as string)}
      />

      {hasCoApplicant && (
        <LoanOptionGroup
          title={`Relationship with ${coApplicantName}`}
          options={APPLICANT_RELATIONSHIP_OPTIONS}
          value={data.applicantRelationship ?? ""}
          onChange={(v) => set("applicantRelationship", v as string)}
        />
      )}

      {showMaritalStatus && (
        <LoanOptionGroup
          title="Marital Status"
          options={MARITAL_STATUS_OPTIONS}
          value={data.maritalStatus ?? ""}
          onChange={(v) => set("maritalStatus", v as string)}
        />
      )}

      {showDependantsSection && (
        <>
          <LoanOptionGroup
            title="Do you have any dependants?"
            options={YES_NO_OPTIONS}
            value={data.hasDependants ?? ""}
            onChange={(v) => handleHasDependantsChange(v as string)}
          />

          {data.hasDependants === "Yes" && (
            <div className="flex flex-col gap-4">
              <FieldRow label="Number of dependants" htmlFor="dependantsCount">
                <Input
                  id="dependantsCount"
                  type="number"
                  inputMode="numeric"
                  min={1}
                  max={MAX_DEPENDANTS}
                  value={data.dependants ?? 1}
                  onChange={(e) => {
                    const v = parseInt(e.target.value, 10);
                    if (!isNaN(v) && v >= 1 && v <= MAX_DEPENDANTS) {
                      handleDependantsCountChange(v);
                    }
                  }}
                />
              </FieldRow>

              {/* Children shared (joint + married/defacto) */}
              {hasCoApplicant && isRelationshipMarriedOrDefacto && (
                <LoanOptionGroup
                  title="Are your dependants shared with the co-applicant?"
                  options={YES_NO_OPTIONS}
                  value={data.childrenShared ?? ""}
                  onChange={(v) => set("childrenShared", v as "Yes" | "No")}
                />
              )}

              {(data.dependantDobs ?? []).map((dob, index) => (
                <FieldRow
                  key={index}
                  label={`Dependant ${index + 1} — Date of Birth`}
                  htmlFor={`dob-${index}`}
                >
                  <DatePicker
                    value={dob ?? undefined}
                    onChange={(date) => handleDependantDobChange(index, date)}
                    placeholder="Select date"
                  />
                </FieldRow>
              ))}
            </div>
          )}
        </>
      )}

      <LoanOptionGroup
        title="Do You Own Property in a Trust or Company?"
        options={PROPERTY_OWNERSHIP_OPTIONS}
        value={data.propertyOwnership ?? ""}
        onChange={(v) => handlePropertyOwnershipChange(v as string)}
      />

      {showPropertyDetails && (
        <div className="flex flex-col gap-4 border border-border p-4">
          <h2 className="text-h6 text-foreground">
            {data.propertyOwnership === "trust"
              ? "Trust Details"
              : "Company Details"}
          </h2>

          <div className="grid grid-cols-2 gap-3">
            <FieldRow
              label={
                data.propertyOwnership === "trust"
                  ? "Trust Name"
                  : "Company Name"
              }
              htmlFor="trustOrCompanyName"
            >
              <Input
                id="trustOrCompanyName"
                value={data.trustOrCompanyName ?? ""}
                onChange={(e) => set("trustOrCompanyName", e.target.value)}
              />
            </FieldRow>

            <FieldRow label="Trading as" htmlFor="tradingAs">
              <Input
                id="tradingAs"
                value={data.tradingAs ?? ""}
                onChange={(e) => set("tradingAs", e.target.value)}
              />
            </FieldRow>

            <FieldRow label="Date Commenced" htmlFor="dateCommenced">
              <Input
                id="dateCommenced"
                placeholder="DD/MM/YYYY"
                value={data.dateCommenced ?? ""}
                onChange={(e) => set("dateCommenced", e.target.value)}
              />
            </FieldRow>

            <FieldRow label="Number of Directors" htmlFor="numberOfDirectors">
              <Input
                id="numberOfDirectors"
                type="number"
                inputMode="numeric"
                min={1}
                value={data.numberOfDirectors ?? ""}
                onChange={(e) =>
                  set(
                    "numberOfDirectors",
                    e.target.value ? parseInt(e.target.value, 10) : null,
                  )
                }
              />
            </FieldRow>

            {data.propertyOwnership === "company" && (
              <FieldRow label="Number of Employees" htmlFor="numberOfEmployees">
                <Input
                  id="numberOfEmployees"
                  type="number"
                  inputMode="numeric"
                  min={0}
                  value={data.numberOfEmployees ?? ""}
                  onChange={(e) =>
                    set(
                      "numberOfEmployees",
                      e.target.value ? parseInt(e.target.value, 10) : null,
                    )
                  }
                />
              </FieldRow>
            )}
          </div>
        </div>
      )}
    </div>
  );
}
