import {
  Alert,
  Button,
  Checkbox,
  Divider,
  Group,
  Loader,
  SimpleGrid,
  Stack,
  Text,
  TextInput,
} from "@mantine/core";
import { zodResolver } from "@hookform/resolvers/zod";
import { useQuery } from "@tanstack/react-query";
import {
  AlertCircle,
  ArrowLeft,
  ArrowRight,
  // UserCheck,
} from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";

import type { AuthUser } from "@/types/auth";
import type { CreateCompanyPayload } from "@/services/companies.service";
import type { ProfileResponse, UpdateProfilePayload } from "@/types/profile";
import type { CompanyRegistrationData } from "@edr/types";
import {
  ControlledPhoneField,
  isValidPhone,
  toEthiopianE164,
} from "@/components/PhoneField";
import { SmartFileInput } from "@edr/ui-common";
import { api } from "@/services/api";
import RoleLicenseStep, {
  type RoleLicenseProfile,
} from "@/components/onboarding/RoleLicenseStep";
import ETradeInfo from "@/components/onboarding/ETradeInfo";

type CompanyStep =
  | "company"
  | "personnel"
  | "contact"
  | "poa"
  | "documents"
  | "additional";

const onboardingSchema = z.object({
  companyFirstName: z.string().min(1, "First name is required"),
  companyLastName: z.string().min(1, "Last name is required"),
  companyEmail: z.string().email("Invalid email address"),
  companyPhone: z
    .string()
    .min(1, "Company phone is required")
    .refine(isValidPhone, "Enter a valid phone number"),
  companyLocation: z.string().min(1, "Location is required"),
  // Derived from the eTrade address parts (kebele/woreda/zone/region); no
  // standalone input — the granular fields live in the registration section.
  companyAddress: z.string().optional(),
  tinNumber: z
    .string()
    .length(10, "TIN must be exactly 10 digits")
    .regex(/^00\d{8}$/, "TIN must be 10 digits starting with 00"),
  vatNumber: z
    .string()
    .min(1, "VAT number is required")
    .length(10, "VAT number must be exactly 10 digits"),
  fanNumber: z.string().length(16, "FAN must be exactly 16 digits"),
  licenceNumber: z.string().optional(),
  statusDescription: z.string().optional(),
  dateRegistered: z.string().optional(),
  renewedFrom: z.string().optional(),
  renewalDate: z.string().optional(),
  renewedTo: z.string().optional(),
  region: z.string().optional(),
  zone: z.string().optional(),
  woreda: z.string().optional(),
  kebele: z.string().optional(),
  houseNo: z.string().optional(),
  etradePhone: z.string().optional(),
  contactPersonFirstName: z
    .string()
    .min(1, "Contact person first name is required"),
  contactPersonLastName: z
    .string()
    .min(1, "Contact person last name is required"),
  contactPersonPosition: z.string().optional(),
  contactPersonEmail: z
    .string()
    .email("Invalid email address")
    .optional()
    .or(z.literal("")),
  contactPersonPhone: z
    .string()
    .min(1, "Contact person phone is required")
    .refine(isValidPhone, "Enter a valid phone number"),
  generalManagerFirstName: z.string().min(1, "GM first name is required"),
  generalManagerLastName: z.string().min(1, "GM last name is required"),
  generalManagerEmail: z.string().email("Invalid GM email"),
  generalManagerPhone: z
    .string()
    .min(1, "GM phone is required")
    .refine(isValidPhone, "Enter a valid phone number"),
  poaFirstName: z.string().optional(),
  poaLastName: z.string().optional(),
  poaPhone: z
    .string()
    .optional()
    .refine((v) => !v || isValidPhone(v), "Enter a valid phone number"),
  poaAddress: z.string().optional(),
  poaEmail: z.string().optional(),
  poaLocation: z.string().optional(),
});

type FormData = z.infer<typeof onboardingSchema>;

const stepFields: Record<CompanyStep, (keyof FormData)[]> = {
  company: [
    "companyFirstName",
    "companyLastName",
    "companyEmail",
    "companyPhone",
    "companyLocation",
    "companyAddress",
    "tinNumber",
    "vatNumber",
    "fanNumber",
    "licenceNumber",
    "statusDescription",
    "dateRegistered",
    "renewedFrom",
    "renewalDate",
    "renewedTo",
    "region",
    "zone",
    "woreda",
    "kebele",
    "houseNo",
    "etradePhone",
  ],
  personnel: [
    "generalManagerFirstName",
    "generalManagerLastName",
    "generalManagerEmail",
    "generalManagerPhone",
  ],
  contact: [
    "contactPersonFirstName",
    "contactPersonLastName",
    "contactPersonPosition",
    "contactPersonEmail",
    "contactPersonPhone",
  ],
  poa: [],
  documents: [],
  additional: [],
};

/** Join first + last into the single name the API stores. */
function joinName(first?: string, last?: string): string {
  return [first?.trim(), last?.trim()].filter(Boolean).join(" ");
}

/** Split a stored single name into first (first token) + last (the rest). */
function splitName(full?: string | null): { first: string; last: string } {
  const trimmed = (full ?? "").trim();
  if (!trimmed) return { first: "", last: "" };
  const idx = trimmed.indexOf(" ");
  if (idx === -1) return { first: trimmed, last: "" };
  return { first: trimmed.slice(0, idx), last: trimmed.slice(idx + 1).trim() };
}

function buildPayload(data: FormData, _user: AuthUser): CreateCompanyPayload {
  return {
    companyName: joinName(data.companyFirstName, data.companyLastName),
    companyEmail: data.companyEmail,
    companyPhone: data.companyPhone,
    companyLocation: data.companyLocation,
    companyAddress: data.companyAddress,
    tin: data.tinNumber,
    vatNumber: data.vatNumber,
    fanNumber: data.fanNumber,
    attributes: {
      contactPersonName: joinName(
        data.contactPersonFirstName,
        data.contactPersonLastName,
      ),
      contactPersonPosition: data.contactPersonPosition || undefined,
      contactPersonEmail: data.contactPersonEmail || undefined,
      contactPersonPhone: data.contactPersonPhone,
      generalManagerName: joinName(
        data.generalManagerFirstName,
        data.generalManagerLastName,
      ),
      generalManagerEmail: data.generalManagerEmail,
      generalManagerPhone: data.generalManagerPhone,
      poaName: joinName(data.poaFirstName, data.poaLastName) || undefined,
      poaPhone: data.poaPhone || undefined,
      poaAddress: data.poaAddress || undefined,
      poaEmail: data.poaEmail || undefined,
      poaLocation: data.poaLocation || undefined,
    },
  };
}

/** Map one wizard step's form values to the profile-update payload it saves. */
function stepPayload(step: CompanyStep, d: FormData): Partial<UpdateProfilePayload> {
  switch (step) {
    case "company":
      return {
        companyName: joinName(d.companyFirstName, d.companyLastName),
        companyEmail: d.companyEmail,
        companyPhone: d.companyPhone,
        companyLocation: d.companyLocation,
        companyAddress: d.companyAddress,
        tin: d.tinNumber,
        vatNumber: d.vatNumber,
        fanNumber: d.fanNumber,
        licenceNumber: d.licenceNumber,
        statusDescription: d.statusDescription,
        dateRegistered: d.dateRegistered,
        renewedFrom: d.renewedFrom,
        renewalDate: d.renewalDate,
        renewedTo: d.renewedTo,
        region: d.region,
        zone: d.zone,
        woreda: d.woreda,
        kebele: d.kebele,
        houseNo: d.houseNo,
        etradePhone: d.etradePhone,
      };
    case "personnel":
      return {
        generalManagerName: joinName(
          d.generalManagerFirstName,
          d.generalManagerLastName,
        ),
        generalManagerEmail: d.generalManagerEmail,
        generalManagerPhone: d.generalManagerPhone,
      };
    case "contact":
      return {
        contactPersonName: joinName(
          d.contactPersonFirstName,
          d.contactPersonLastName,
        ),
        contactPersonPosition: d.contactPersonPosition || undefined,
        contactPersonEmail: d.contactPersonEmail || undefined,
        contactPersonPhone: d.contactPersonPhone,
      };
    case "poa":
      return {
        poaName: joinName(d.poaFirstName, d.poaLastName) || undefined,
        poaPhone: d.poaPhone || undefined,
        poaEmail: d.poaEmail || undefined,
        poaLocation: d.poaLocation || undefined,
        poaAddress: d.poaAddress || undefined,
      };
    default:
      return {};
  }
}

/** Seed the form from previously-saved profile data. */
function toFormValues(p: ProfileResponse): FormData {
  // The draft placeholder TIN ("D…") shouldn't show as a real value.
  const tin = p.tinNumber && !p.tinNumber.startsWith("D") ? p.tinNumber : "";
  const companyN = splitName(p.companyName);
  const contactN = splitName(p.contactPersonName);
  const gmN = splitName(p.generalManagerName);
  const poaN = splitName(p.poaName);
  return {
    companyFirstName: companyN.first,
    companyLastName: companyN.last,
    companyEmail: p.companyEmail ?? "",
    companyPhone: p.companyPhone ?? "",
    companyLocation: p.companyLocation ?? "",
    companyAddress: p.companyAddress ?? "",
    tinNumber: tin,
    vatNumber: p.vatNumber ?? "",
    fanNumber: p.fanNumber ?? "",
    licenceNumber: p.licenceNumber ?? "",
    statusDescription: p.statusDescription ?? "",
    dateRegistered: p.dateRegistered ?? "",
    renewedFrom: p.renewedFrom ?? "",
    renewalDate: p.renewalDate ?? "",
    renewedTo: p.renewedTo ?? "",
    region: p.region ?? "",
    zone: p.zone ?? "",
    woreda: p.woreda ?? "",
    kebele: p.kebele ?? "",
    houseNo: p.houseNo ?? "",
    etradePhone: p.etradePhone ?? "",
    contactPersonFirstName: contactN.first,
    contactPersonLastName: contactN.last,
    contactPersonPosition: p.contactPersonPosition ?? "",
    contactPersonEmail: p.contactPersonEmail ?? "",
    contactPersonPhone: p.contactPersonPhone ?? "",
    generalManagerFirstName: gmN.first,
    generalManagerLastName: gmN.last,
    generalManagerEmail: p.generalManagerEmail ?? "",
    generalManagerPhone: p.generalManagerPhone ?? "",
    poaFirstName: poaN.first,
    poaLastName: poaN.last,
    poaPhone: p.poaPhone ?? "",
    poaAddress: p.poaAddress ?? "",
    poaEmail: p.poaEmail ?? "",
    poaLocation: p.poaLocation ?? "",
  };
}

export default function CompanyProfileForm({
  documentSettingCode,
  documentFiles: controlledFiles,
  onDocumentFilesChange,
  user,
  onSubmit,
  isPending,
  onBack,
  initialStep,
  resyncOpen,
  hideFirstStepBack,
  onStepChange,
  onSaveStep,
  rehydrate,
  roleProfiles,
  licenseFiles,
  onLicenseChange,
}: {
  documentSettingCode: string;
  documentFiles?: Record<string, File | File[] | null>;
  onDocumentFilesChange?: (files: Record<string, File | File[] | null>) => void;
  user: AuthUser;
  onSubmit: (data: CreateCompanyPayload) => void;
  isPending: boolean;
  onBack: () => void;
  /** Step to resume at (defaults to "company"). */
  initialStep?: CompanyStep;
  /** When this flips true (dialog reopened), jump back to initialStep (furthest reached). */
  resyncOpen?: boolean;
  /** Hide the Back button on the first step (onboarding can't go back to role pick). */
  hideFirstStepBack?: boolean;
  /** Reports the active step so the parent can persist resume progress. */
  onStepChange?: (step: CompanyStep) => void;
  /** Persist the current step's data before advancing; returns an error to show. */
  onSaveStep?: (
    data: Partial<UpdateProfilePayload>,
  ) => Promise<{ ok: true } | { ok: false; error: string }>;
  /** Saved profile to seed the form with (rehydration after refresh). */
  rehydrate?: ProfileResponse | null;
  /** Operational profiles for the final per-role license step. */
  roleProfiles?: RoleLicenseProfile[];
  /** Newly-selected license files per profile id. */
  licenseFiles?: Record<string, File[]>;
  onLicenseChange?: (value: Record<string, File[]>) => void;
}) {
  const [step, setStep] = useState<CompanyStep>(initialStep ?? "company");
  const [saving, setSaving] = useState(false);
  const [saveError, setSaveError] = useState<string | null>(null);

  // Report each step change up so the wizard can persist it for resume.
  useEffect(() => {
    onStepChange?.(step);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [step]);

  // On reopen, jump to the furthest step reached (initialStep) so progress
  // never appears to reset.
  const wasOpen = useRef(resyncOpen);
  useEffect(() => {
    if (resyncOpen && !wasOpen.current && initialStep) {
      setStep(initialStep);
      setSaveError(null);
    }
    wasOpen.current = resyncOpen;
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [resyncOpen]);
  const [internalFiles, setInternalFiles] = useState<
    Record<string, File | File[] | null>
  >({});
  const documentFiles = controlledFiles ?? internalFiles;
  const setDocumentFiles = onDocumentFilesChange ?? setInternalFiles;

  const { data: uploadSetting, isLoading: loadingDocuments } = useQuery(
    api.fileUploadSettings.getByCode.queryOptions({
      input: { code: documentSettingCode },
      refetchOnMount: false,
    }),
  );

  const {
    register,
    control,
    handleSubmit,
    trigger,
    watch,
    setValue,
    formState: { errors },
  } = useForm<FormData>({
    resolver: zodResolver(onboardingSchema),
    defaultValues: {
      companyFirstName: "",
      companyLastName: "",
      companyEmail: "",
      companyPhone: "",
      companyLocation: "",
      companyAddress: "",
      tinNumber: "",
      vatNumber: "",
      fanNumber: "",
      licenceNumber: "",
      statusDescription: "",
      dateRegistered: "",
      renewedFrom: "",
      renewalDate: "",
      renewedTo: "",
      region: "",
      zone: "",
      woreda: "",
      kebele: "",
      houseNo: "",
      etradePhone: "",
      contactPersonFirstName: "",
      contactPersonLastName: "",
      contactPersonPosition: "",
      contactPersonEmail: "",
      contactPersonPhone: "",
      generalManagerFirstName: "",
      generalManagerLastName: "",
      generalManagerEmail: "",
      generalManagerPhone: "",
      poaFirstName: "",
      poaLastName: "",
      poaPhone: "",
      poaAddress: "",
      poaEmail: "",
      poaLocation: "",
    },
    // Rehydrate from previously-saved data (RHF re-syncs when `values` change).
    values: rehydrate ? toFormValues(rehydrate) : undefined,
  });

  // The business owner/manager pulled from eTrade — powers "Use owner as
  // manager" on the General Manager step.
  const [etradeOwner, setEtradeOwner] = useState<{
    name: string;
    phone: string;
    email?: string;
  } | null>(null);

  // Mirror the three "copy from previous person" checkboxes.
  const [ownerIsGm, setOwnerIsGm] = useState(false);
  const [gmIsContact, setGmIsContact] = useState(false);
  const [contactIsPoa, setContactIsPoa] = useState(false);

  const handleETradeDataLoaded = (data: CompanyRegistrationData) => {
    // Company name comes from the eTrade manager/owner name on the license.
    if (data.managerName) {
      const { first, last } = splitName(data.managerName);
      setValue("companyFirstName", first, { shouldValidate: true });
      setValue("companyLastName", last, { shouldValidate: true });
    }
    setValue("licenceNumber", data.licenceNumber);
    setValue("statusDescription", data.statusDescription);
    setValue("dateRegistered", data.dateRegistered);
    setValue("renewedFrom", data.renewedFrom);
    setValue("renewalDate", data.renewalDate);
    setValue("renewedTo", data.renewedTo);
    setValue("region", data.region);
    setValue("zone", data.zone);
    setValue("woreda", data.woreda);
    setValue("kebele", data.kebele);
    setValue("houseNo", data.houseNo);
    setValue(
      "etradePhone",
      toEthiopianE164(data.regularPhone || data.mobilePhone),
    );

    // Compose a readable company address from the granular eTrade parts.
    const addressParts = [
      data.houseNo,
      data.kebele,
      data.woreda,
      data.zone,
      data.region,
    ].filter((part) => part && part.trim());
    if (addressParts.length) {
      setValue("companyAddress", addressParts.join(", "));
    }

    // Pre-fill the company contact phone from eTrade's mobile number.
    const mobile = toEthiopianE164(data.mobilePhone || data.regularPhone);
    if (mobile) {
      setValue("companyPhone", mobile, { shouldValidate: true });
    }

    setEtradeOwner({
      name: data.managerName,
      phone: toEthiopianE164(
        data.managerPhone || data.regularPhone || data.mobilePhone,
      ),
      email: data.managerEmail || undefined,
    });
  };

  /** Fill the General Manager from the eTrade business owner. */
  const toggleOwnerAsGm = (checked: boolean) => {
    setOwnerIsGm(checked);
    if (!checked || !etradeOwner) return;
    const { first, last } = splitName(etradeOwner.name);
    setValue("generalManagerFirstName", first, { shouldValidate: true });
    setValue("generalManagerLastName", last, { shouldValidate: true });
    setValue("generalManagerEmail", etradeOwner.email ?? "", {
      shouldValidate: true,
    });
    setValue("generalManagerPhone", etradeOwner.phone ?? "", {
      shouldValidate: true,
    });
  };

  /** Copy the General Manager into the Contact Person fields (toggleable). */
  const toggleGmAsContact = (checked: boolean) => {
    setGmIsContact(checked);
    if (!checked) return;
    setValue("contactPersonFirstName", watch("generalManagerFirstName"));
    setValue("contactPersonLastName", watch("generalManagerLastName"));
    setValue("contactPersonEmail", watch("generalManagerEmail"));
    setValue("contactPersonPhone", watch("generalManagerPhone"));
  };

  /** Copy the Contact Person into the PoA fields (toggleable, still editable). */
  const toggleContactAsPoa = (checked: boolean) => {
    setContactIsPoa(checked);
    if (!checked) return;
    setValue("poaFirstName", watch("contactPersonFirstName"));
    setValue("poaLastName", watch("contactPersonLastName"));
    setValue("poaEmail", watch("contactPersonEmail"));
    setValue("poaPhone", watch("contactPersonPhone"));
  };

  const hasDocuments = Boolean(uploadSetting?.fields?.length);

  // Single source of truth for step sequence — navigation, labels and the
  // progress bar all derive from this so adding/removing a step is one edit.
  const stepOrder: CompanyStep[] = [
    "company",
    "personnel",
    "contact",
    "poa",
    "documents",
    "additional",
  ];
  const currentIdx = stepOrder.indexOf(step);

  /** Validate + persist the current step, returning whether we may advance. */
  const saveCurrentStep = async (): Promise<boolean> => {
    setSaveError(null);
    const isValid = await trigger(stepFields[step]);
    if (!isValid) return false;
    if (!onSaveStep) return true;
    setSaving(true);
    try {
      const res = await onSaveStep(stepPayload(step, watch()));
      if (!res.ok) {
        setSaveError(res.error);
        return false;
      }
      return true;
    } finally {
      setSaving(false);
    }
  };

  // Every role needs at least one license file (existing or newly selected).
  const licenseComplete = (roleProfiles ?? []).every(
    (p) =>
      (licenseFiles?.[p.id]?.length ?? 0) > 0 || p.existingFiles.length > 0,
  );

  const nextStep = async () => {
    if (step === "additional") {
      if (!licenseComplete) {
        setSaveError(
          "Please upload a business license for each of your operational profiles.",
        );
        return;
      }
      handleSubmit((data) => onSubmit(buildPayload(data, user)))();
      return;
    }
    // The documents step has nothing to persist; field steps validate + save
    // before advancing.
    if (step !== "documents") {
      const ok = await saveCurrentStep();
      if (!ok) return;
    }
    setStep(stepOrder[currentIdx + 1]);
  };

  const prevStep = () => {
    setSaveError(null);
    if (currentIdx === 0) onBack();
    else setStep(stepOrder[currentIdx - 1]);
  };

  // Back is hidden on the first step during onboarding (can't return to role
  // selection); otherwise always available.
  const showBack = !(hideFirstStepBack && step === "company");

  return (
    <>
      <form onSubmit={(e) => e.preventDefault()}>
        <Stack gap="md">
          {step === "company" && (
            <>
              <Text fw={600} size="sm" c="edr-text">
                Enter your TIN to auto-fill company information from eTrade
              </Text>
              <ETradeInfo
                tin={watch("tinNumber")}
                register={register("tinNumber")}
                error={errors.tinNumber?.message}
                onDataLoaded={handleETradeDataLoaded}
              />

              <Divider my="sm" />

              <SimpleGrid cols={2} spacing="md">
                <TextInput
                  label={<>First Name <span style={{ color: "var(--mantine-color-red-6)" }}>*</span></>}
                  placeholder="Global"
                  error={errors.companyFirstName?.message}
                  {...register("companyFirstName")}
                />
                <TextInput
                  label={<>Last Name <span style={{ color: "var(--mantine-color-red-6)" }}>*</span></>}
                  placeholder="Logistics Ltd"
                  error={errors.companyLastName?.message}
                  {...register("companyLastName")}
                />
              </SimpleGrid>
              <SimpleGrid cols={2} spacing="md">
                <TextInput
                  label={<>Company Email <span style={{ color: "var(--mantine-color-red-6)" }}>*</span></>}
                  type="email"
                  placeholder="ops@company.com"
                  error={errors.companyEmail?.message}
                  {...register("companyEmail")}
                />
                <ControlledPhoneField
                  control={control}
                  name="companyPhone"
                  label="Company Phone"
                  required
                />
              </SimpleGrid>
              <TextInput
                label={<>Location <span style={{ color: "var(--mantine-color-red-6)" }}>*</span></>}
                placeholder="Addis Ababa, Ethiopia"
                error={errors.companyLocation?.message}
                {...register("companyLocation")}
              />
              <SimpleGrid cols={2} spacing="md">
                <TextInput
                  label={<>VAT Number <span style={{ color: "var(--mantine-color-red-6)" }}>*</span></>}
                  placeholder="VAT-12345"
                  maxLength={10}
                  error={errors.vatNumber?.message}
                  {...register("vatNumber")}
                />
                <TextInput
                  label={<>FAN Number (16 digits) <span style={{ color: "var(--mantine-color-red-6)" }}>*</span></>}
                  placeholder="1234567890123456"
                  maxLength={16}
                  error={errors.fanNumber?.message}
                  {...register("fanNumber")}
                />
              </SimpleGrid>

              <>
                  <Divider my="sm" />
                  <Text fw={600} size="sm" c="edr-text">
                    Registration Details
                  </Text>
                  <Text size="xs" c="edr-muted">
                    Auto-filled from eTrade — these fields cannot be edited.
                  </Text>
                  <SimpleGrid cols={2} spacing="md">
                    <TextInput
                      label="License Number"
                      readOnly
                      styles={{ input: { backgroundColor: "var(--mantine-color-gray-0)", cursor: "default" } }}
                      error={errors.licenceNumber?.message}
                      {...register("licenceNumber")}
                    />
                    <TextInput
                      label="Status"
                      readOnly
                      styles={{ input: { backgroundColor: "var(--mantine-color-gray-0)", cursor: "default" } }}
                      error={errors.statusDescription?.message}
                      {...register("statusDescription")}
                    />
                  </SimpleGrid>
                  <SimpleGrid cols={2} spacing="md">
                    <TextInput
                      label="Date Registered"
                      readOnly
                      styles={{ input: { backgroundColor: "var(--mantine-color-gray-0)", cursor: "default" } }}
                      error={errors.dateRegistered?.message}
                      {...register("dateRegistered")}
                    />
                    <TextInput
                      label="Renewal Date"
                      readOnly
                      styles={{ input: { backgroundColor: "var(--mantine-color-gray-0)", cursor: "default" } }}
                      error={errors.renewalDate?.message}
                      {...register("renewalDate")}
                    />
                  </SimpleGrid>
                  <SimpleGrid cols={2} spacing="md">
                    <TextInput
                      label="Renewed From"
                      readOnly
                      styles={{ input: { backgroundColor: "var(--mantine-color-gray-0)", cursor: "default" } }}
                      error={errors.renewedFrom?.message}
                      {...register("renewedFrom")}
                    />
                    <TextInput
                      label="Renewed To"
                      readOnly
                      styles={{ input: { backgroundColor: "var(--mantine-color-gray-0)", cursor: "default" } }}
                      error={errors.renewedTo?.message}
                      {...register("renewedTo")}
                    />
                  </SimpleGrid>

                  <Text fw={600} size="sm" c="edr-text" mt="md">
                    Address Information
                  </Text>
                  <SimpleGrid cols={2} spacing="md">
                    <TextInput
                      label="Region"
                      readOnly
                      styles={{ input: { backgroundColor: "var(--mantine-color-gray-0)", cursor: "default" } }}
                      error={errors.region?.message}
                      {...register("region")}
                    />
                    <TextInput
                      label="Zone"
                      readOnly
                      styles={{ input: { backgroundColor: "var(--mantine-color-gray-0)", cursor: "default" } }}
                      error={errors.zone?.message}
                      {...register("zone")}
                    />
                  </SimpleGrid>
                  <SimpleGrid cols={2} spacing="md">
                    <TextInput
                      label="Woreda"
                      readOnly
                      styles={{ input: { backgroundColor: "var(--mantine-color-gray-0)", cursor: "default" } }}
                      error={errors.woreda?.message}
                      {...register("woreda")}
                    />
                    <TextInput
                      label="Kebele"
                      readOnly
                      styles={{ input: { backgroundColor: "var(--mantine-color-gray-0)", cursor: "default" } }}
                      error={errors.kebele?.message}
                      {...register("kebele")}
                    />
                  </SimpleGrid>
                  <SimpleGrid cols={2} spacing="md">
                    <TextInput
                      label="House No"
                      readOnly
                      styles={{ input: { backgroundColor: "var(--mantine-color-gray-0)", cursor: "default" } }}
                      error={errors.houseNo?.message}
                      {...register("houseNo")}
                    />
                    <ControlledPhoneField
                      control={control}
                      name="etradePhone"
                      label="Phone"
                    />
                  </SimpleGrid>
                </>
            </>
          )}

          {step === "personnel" && (
            <>
              <Text fw={600} size="sm" c="edr-text">
                General Manager
              </Text>
              <Checkbox
                color="edr-green"
                label="Use eTrade business owner as General Manager"
                checked={ownerIsGm}
                disabled={!etradeOwner}
                onChange={(e) => toggleOwnerAsGm(e.currentTarget.checked)}
              />
              <SimpleGrid cols={2} spacing="md">
                <TextInput
                  label={<>First Name <span style={{ color: "var(--mantine-color-red-6)" }}>*</span></>}
                  placeholder="Abebe"
                  error={errors.generalManagerFirstName?.message}
                  {...register("generalManagerFirstName")}
                />
                <TextInput
                  label={<>Last Name <span style={{ color: "var(--mantine-color-red-6)" }}>*</span></>}
                  placeholder="Bikila"
                  error={errors.generalManagerLastName?.message}
                  {...register("generalManagerLastName")}
                />
              </SimpleGrid>
              <SimpleGrid cols={2} spacing="md">
                <TextInput
                  label={<>Email <span style={{ color: "var(--mantine-color-red-6)" }}>*</span></>}
                  type="email"
                  placeholder="gm@company.com"
                  error={errors.generalManagerEmail?.message}
                  {...register("generalManagerEmail")}
                />
                <ControlledPhoneField
                  control={control}
                  name="generalManagerPhone"
                  label="Phone"
                  required
                />
              </SimpleGrid>
            </>
          )}

          {step === "contact" && (
            <>
              <Text fw={600} size="sm" c="edr-text">
                Contact Person
              </Text>
              <Checkbox
                color="edr-green"
                label="Use General Manager as contact person"
                checked={gmIsContact}
                onChange={(e) => toggleGmAsContact(e.currentTarget.checked)}
              />
              <SimpleGrid cols={2} spacing="md">
                <TextInput
                  label={<>First Name <span style={{ color: "var(--mantine-color-red-6)" }}>*</span></>}
                  placeholder="Jane"
                  error={errors.contactPersonFirstName?.message}
                  {...register("contactPersonFirstName")}
                />
                <TextInput
                  label={<>Last Name <span style={{ color: "var(--mantine-color-red-6)" }}>*</span></>}
                  placeholder="Smith"
                  error={errors.contactPersonLastName?.message}
                  {...register("contactPersonLastName")}
                />
              </SimpleGrid>
              <SimpleGrid cols={2} spacing="md">
                <TextInput
                  label="Position (Optional)"
                  placeholder="Operations Lead"
                  error={errors.contactPersonPosition?.message}
                  {...register("contactPersonPosition")}
                />
                <TextInput
                  label="Email (Optional)"
                  type="email"
                  placeholder="contact@company.com"
                  error={errors.contactPersonEmail?.message}
                  {...register("contactPersonEmail")}
                />
              </SimpleGrid>
              <SimpleGrid cols={2} spacing="md">
                <ControlledPhoneField
                  control={control}
                  name="contactPersonPhone"
                  label="Phone"
                  required
                />
              </SimpleGrid>
            </>
          )}

          {step === "poa" && (
            <>
              <Text size="sm" c="edr-muted">
                Power of Attorney details are optional. Fill them in if you have
                them, or skip to continue.
              </Text>
              <Checkbox
                color="edr-green"
                label="Use contact person as Power of Attorney"
                checked={contactIsPoa}
                onChange={(e) => toggleContactAsPoa(e.currentTarget.checked)}
              />
              <SimpleGrid cols={2} spacing="md">
                <TextInput
                  label="PoA First Name"
                  placeholder="First name"
                  error={errors.poaFirstName?.message}
                  {...register("poaFirstName")}
                />
                <TextInput
                  label="PoA Last Name"
                  placeholder="Last name"
                  error={errors.poaLastName?.message}
                  {...register("poaLastName")}
                />
              </SimpleGrid>
              <SimpleGrid cols={2} spacing="md">
                <TextInput
                  label="PoA Email"
                  type="email"
                  placeholder="poa@company.com"
                  error={errors.poaEmail?.message}
                  {...register("poaEmail")}
                />
                <ControlledPhoneField
                  control={control}
                  name="poaPhone"
                  label="PoA Phone"
                />
              </SimpleGrid>
              <SimpleGrid cols={2} spacing="md">
                <TextInput
                  label="PoA Location"
                  placeholder="City, Country"
                  error={errors.poaLocation?.message}
                  {...register("poaLocation")}
                />
                <TextInput
                  label="PoA Address"
                  placeholder="Full Address"
                  error={errors.poaAddress?.message}
                  {...register("poaAddress")}
                />
              </SimpleGrid>
            </>
          )}

          {step === "documents" && (
            <>
              {loadingDocuments ? (
                <Group justify="center" py="xl">
                  <Loader size="sm" color="edr-green" />
                </Group>
              ) : !uploadSetting ? (
                <Text size="sm" c="edr-muted" ta="center" py="md">
                  No document requirements found for your account type.
                </Text>
              ) : (
                <SmartFileInput
                  file={uploadSetting}
                  value={documentFiles}
                  onChange={setDocumentFiles}
                />
              )}
            </>
          )}

          {step === "additional" && (
            <RoleLicenseStep
              profiles={roleProfiles ?? []}
              value={licenseFiles ?? {}}
              onChange={onLicenseChange ?? (() => {})}
            />
          )}

          {saveError && (
            <Alert
              color="red"
              variant="light"
              icon={<AlertCircle size={18} />}
              title={
                step === "additional"
                  ? "Business license required"
                  : "Couldn't save this step"
              }
            >
              {saveError}
            </Alert>
          )}

          <Group justify="space-between" pt="xs">
            {showBack ? (
              <Button
                variant="default"
                onClick={prevStep}
                leftSection={<ArrowLeft size={16} />}
              >
                {step === "additional" ? "Back to Documents" : "Back"}
              </Button>
            ) : (
              <span />
            )}
            <Button
              color="edr-green"
              onClick={nextStep}
              disabled={
                isPending ||
                saving ||
                (step === "documents" && !hasDocuments && loadingDocuments)
              }
              loading={isPending || saving}
              rightSection={
                !isPending &&
                !saving &&
                step !== "additional" &&
                step !== "documents" ? (
                  <ArrowRight size={16} />
                ) : undefined
              }
            >
              {step === "documents"
                ? "Continue"
                : step === "additional"
                  ? "Finish onboarding"
                  : "Save & Continue"}
            </Button>
          </Group>
        </Stack>
      </form>
    </>
  );
}
