import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";

import {
  ArrowLeft,
  ArrowRight,
  Building2,
  User,
  FileText,
  CheckCircle2,
} from "lucide-react";

import { ControlledPhoneField, isValidPhone } from "@/components/PhoneField";

import {
  Button,
  Field,
  FieldError,
  FieldGroup,
  FieldLabel,
  Input,
} from "@edr/ui-common";

type OnboardingStep =
  | "personal"
  | "company"
  | "personnel"
  | "poa";

const onboardingSchema = z.object({
  // PERSONAL
  firstName: z.string().min(1, "First name is required"),
  lastName: z.string().min(1, "Last name is required"),
  email: z.string().email("Invalid email address"),
  phoneNumber: z
    .string()
    .min(1, "Phone number is required")
    .refine(isValidPhone, "Enter a valid phone number"),

  // COMPANY
  companyName: z.string().min(1, "Company 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"),
  companyAddress: z.string().min(1, "Address is required"),

  // LEGAL
  tinNumber: z.string().regex(/^\d{10}$/, {
    message: "TIN must be exactly 10 digits",
  }),

  vatNumber: z.string().min(1, "VAT number is required"),

  fanNumber: z.string().regex(/^\d{16}$/, {
    message: "FAN must be exactly 16 digits",
  }),

  // CONTACT PERSON
  contactPersonName: z
    .string()
    .min(1, "Contact person name is required"),

  contactPersonPhone: z
    .string()
    .min(1, "Contact person phone is required")
    .refine(isValidPhone, "Enter a valid phone number"),

  // GENERAL MANAGER
  generalManagerName: z
    .string()
    .min(1, "General manager name is required"),

  generalManagerEmail: z
    .string()
    .email("Invalid email"),

  generalManagerPhone: z
    .string()
    .min(1, "General manager phone is required")
    .refine(isValidPhone, "Enter a valid phone number"),

  // OPTIONAL POA
  poaName: 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<
  OnboardingStep,
  (keyof FormData)[]
> = {
  personal: [
    "firstName",
    "lastName",
    "email",
    "phoneNumber",
  ],

  company: [
    "companyName",
    "companyEmail",
    "companyPhone",
    "companyLocation",
    "companyAddress",
    "tinNumber",
    "vatNumber",
    "fanNumber",
  ],

  personnel: [
    "contactPersonName",
    "contactPersonPhone",
    "generalManagerName",
    "generalManagerEmail",
    "generalManagerPhone",
  ],

  poa: [],
};

export default function ImportExportOnBoarding() {
  const [step, setStep] =
    useState<OnboardingStep>("personal");

  const {
    register,
    control,
    handleSubmit,
    trigger,
    formState: { errors, isSubmitting },
  } = useForm<FormData>({
    resolver: zodResolver(onboardingSchema),

    defaultValues: {
      phoneNumber: "",
      companyPhone: "",
      contactPersonPhone: "",
      generalManagerPhone: "",
      poaPhone: "",
    },
  });

  const nextStep = async () => {
    if (step === "poa") {
      handleSubmit(onSubmit)();
      return;
    }

    const isValid = await trigger(stepFields[step]);

    if (!isValid) return;

    if (step === "personal") {
      setStep("company");
    } else if (step === "company") {
      setStep("personnel");
    } else {
      setStep("poa");
    }
  };

  const prevStep = () => {
    if (step === "company") {
      setStep("personal");
    } else if (step === "personnel") {
      setStep("company");
    } else if (step === "poa") {
      setStep("personnel");
    }
  };

  const onSubmit = async (data: FormData) => {
    console.log(data);
  };

  return (
    <>
      {/* STEP HEADER */}
      <div className="mb-8">
        <div className="flex items-center justify-between max-w-2xl mx-auto relative px-2">
          <div className="absolute top-1/2 left-0 w-full h-0.5 bg-border -translate-y-1/2 z-0" />

          <StepIcon
            icon={<User className="size-5" />}
            active={step === "personal"}
            completed={
              step !== "personal"
            }
          />

          <StepIcon
            icon={<Building2 className="size-5" />}
            active={step === "company"}
            completed={
              step === "personnel" ||
              step === "poa"
            }
          />

          <StepIcon
            icon={<User className="size-5" />}
            active={step === "personnel"}
            completed={step === "poa"}
          />

          <StepIcon
            icon={<FileText className="size-5" />}
            active={step === "poa"}
            completed={false}
          />
        </div>

        <p className="text-center text-sm text-muted-foreground mt-3">
          {step === "personal" &&
            "Step 1 of 4 — Personal Information"}

          {step === "company" &&
            "Step 2 of 4 — Company Information"}

          {step === "personnel" &&
            "Step 3 of 4 — Personnel Information"}

          {step === "poa" &&
            "Step 4 of 4 — Power of Attorney"}
        </p>
      </div>

      <form
        onSubmit={handleSubmit(onSubmit)}
        className="flex flex-col gap-4"
      >
        <FieldGroup className="gap-4">
          {/* PERSONAL */}
          {step === "personal" && (
            <>
              <div className="grid grid-cols-2 gap-4">
                <Field
                  data-invalid={Boolean(
                    errors.firstName
                  )}
                >
                  <FieldLabel>
                    First Name
                  </FieldLabel>

                  <Input
                    placeholder="John"
                    {...register("firstName")}
                  />

                  <FieldError
                    errors={[errors.firstName]}
                  />
                </Field>

                <Field
                  data-invalid={Boolean(
                    errors.lastName
                  )}
                >
                  <FieldLabel>
                    Last Name
                  </FieldLabel>

                  <Input
                    placeholder="Doe"
                    {...register("lastName")}
                  />

                  <FieldError
                    errors={[errors.lastName]}
                  />
                </Field>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <Field
                  data-invalid={Boolean(
                    errors.email
                  )}
                >
                  <FieldLabel>Email</FieldLabel>

                  <Input
                    type="email"
                    placeholder="john@example.com"
                    {...register("email")}
                  />

                  <FieldError
                    errors={[errors.email]}
                  />
                </Field>

                <ControlledPhoneField
                  control={control}
                  name="phoneNumber"
                  label="Phone Number"
                  required
                />
              </div>
            </>
          )}

          {/* COMPANY */}
          {step === "company" && (
            <>
              <Field
                data-invalid={Boolean(
                  errors.companyName
                )}
              >
                <FieldLabel>
                  Company Name
                </FieldLabel>

                <Input
                  placeholder="Global Logistics Ltd"
                  {...register("companyName")}
                />

                <FieldError
                  errors={[errors.companyName]}
                />
              </Field>

              <div className="grid grid-cols-2 gap-4">
                <Field
                  data-invalid={Boolean(
                    errors.companyEmail
                  )}
                >
                  <FieldLabel>
                    Company Email
                  </FieldLabel>

                  <Input
                    type="email"
                    placeholder="ops@company.com"
                    {...register(
                      "companyEmail"
                    )}
                  />

                  <FieldError
                    errors={[errors.companyEmail]}
                  />
                </Field>

                <ControlledPhoneField
                  control={control}
                  name="companyPhone"
                  label="Company Phone"
                  required
                />
              </div>

              <div className="grid grid-cols-2 gap-4">
                <Field
                  data-invalid={Boolean(
                    errors.companyLocation
                  )}
                >
                  <FieldLabel>
                    Company Location
                  </FieldLabel>

                  <Input
                    placeholder="Addis Ababa"
                    {...register(
                      "companyLocation"
                    )}
                  />

                  <FieldError
                    errors={[
                      errors.companyLocation,
                    ]}
                  />
                </Field>

                <Field
                  data-invalid={Boolean(
                    errors.companyAddress
                  )}
                >
                  <FieldLabel>
                    Company Address
                  </FieldLabel>

                  <Input
                    placeholder="Bole, Woreda 03"
                    {...register(
                      "companyAddress"
                    )}
                  />

                  <FieldError
                    errors={[
                      errors.companyAddress,
                    ]}
                  />
                </Field>
              </div>

              <div className="grid grid-cols-3 gap-4">
                <Field
                  data-invalid={Boolean(
                    errors.tinNumber
                  )}
                >
                  <FieldLabel>
                    TIN Number
                  </FieldLabel>

                  <Input
                    maxLength={10}
                    placeholder="1234567890"
                    {...register("tinNumber")}
                  />

                  <FieldError
                    errors={[errors.tinNumber]}
                  />
                </Field>

                <Field
                  data-invalid={Boolean(
                    errors.vatNumber
                  )}
                >
                  <FieldLabel>
                    VAT Number
                  </FieldLabel>

                  <Input
                    placeholder="VAT123456"
                    {...register("vatNumber")}
                  />

                  <FieldError
                    errors={[errors.vatNumber]}
                  />
                </Field>

                <Field
                  data-invalid={Boolean(
                    errors.fanNumber
                  )}
                >
                  <FieldLabel>
                    FAN Number
                  </FieldLabel>

                  <Input
                    maxLength={16}
                    placeholder="1234567890123456"
                    {...register("fanNumber")}
                  />

                  <FieldError
                    errors={[errors.fanNumber]}
                  />
                </Field>
              </div>
            </>
          )}

          {/* PERSONNEL */}
          {step === "personnel" && (
            <>
              <div>
                <h3 className="text-sm font-semibold text-foreground mb-3">
                  Contact Person
                </h3>

                <div className="grid grid-cols-2 gap-4">
                  <Field
                    data-invalid={Boolean(
                      errors.contactPersonName
                    )}
                  >
                    <FieldLabel>
                      Contact Person Name
                    </FieldLabel>

                    <Input
                      placeholder="Jane Smith"
                      {...register(
                        "contactPersonName"
                      )}
                    />

                    <FieldError
                      errors={[
                        errors.contactPersonName,
                      ]}
                    />
                  </Field>

                  <ControlledPhoneField
                    control={control}
                    name="contactPersonPhone"
                    label="Contact Person Phone"
                    required
                  />
                </div>
              </div>

              <hr className="border-border" />

              <div>
                <h3 className="text-sm font-semibold text-foreground mb-3">
                  General Manager
                </h3>

                <div className="grid grid-cols-2 gap-4">
                  <Field
                    className="col-span-2"
                    data-invalid={Boolean(
                      errors.generalManagerName
                    )}
                  >
                    <FieldLabel>
                      General Manager Name
                    </FieldLabel>

                    <Input
                      placeholder="Abebe Bikila"
                      {...register(
                        "generalManagerName"
                      )}
                    />

                    <FieldError
                      errors={[
                        errors.generalManagerName,
                      ]}
                    />
                  </Field>

                  <Field
                    data-invalid={Boolean(
                      errors.generalManagerEmail
                    )}
                  >
                    <FieldLabel>
                      General Manager Email
                    </FieldLabel>

                    <Input
                      type="email"
                      placeholder="gm@company.com"
                      {...register(
                        "generalManagerEmail"
                      )}
                    />

                    <FieldError
                      errors={[
                        errors.generalManagerEmail,
                      ]}
                    />
                  </Field>

                  <ControlledPhoneField
                    control={control}
                    name="generalManagerPhone"
                    label="General Manager Phone"
                    required
                  />
                </div>
              </div>
            </>
          )}

          {/* POA */}
          {step === "poa" && (
            <>
              <p className="text-sm text-muted-foreground">
                Power of Attorney details are
                optional.
              </p>

              <Field>
                <FieldLabel>PoA Name</FieldLabel>

                <Input
                  placeholder="Authorized Representative"
                  {...register("poaName")}
                />
              </Field>

              <div className="grid grid-cols-2 gap-4">
                <Field>
                  <FieldLabel>
                    PoA Email
                  </FieldLabel>

                  <Input
                    type="email"
                    placeholder="poa@company.com"
                    {...register("poaEmail")}
                  />
                </Field>

                <ControlledPhoneField
                  control={control}
                  name="poaPhone"
                  label="PoA Phone"
                />
              </div>

              <div className="grid grid-cols-2 gap-4">
                <Field>
                  <FieldLabel>
                    PoA Location
                  </FieldLabel>

                  <Input
                    placeholder="City, Country"
                    {...register("poaLocation")}
                  />
                </Field>

                <Field>
                  <FieldLabel>
                    PoA Address
                  </FieldLabel>

                  <Input
                    placeholder="Full Address"
                    {...register("poaAddress")}
                  />
                </Field>
              </div>
            </>
          )}
        </FieldGroup>

        {/* FOOTER */}
        <div className="flex items-center justify-between pt-2">
          <Button
            type="button"
            variant="outline"
            onClick={prevStep}
            disabled={step === "personal"}
          >
            <ArrowLeft />
            Back
          </Button>

          <Button
            type="button"
            onClick={nextStep}
            disabled={isSubmitting}
          >
            {step === "poa" ? (
              "Complete Registration"
            ) : (
              <>
                Next Step
                <ArrowRight />
              </>
            )}
          </Button>
        </div>
      </form>
    </>
  );
}

function StepIcon({
  icon,
  active,
  completed,
}: {
  icon: React.ReactNode;
  active: boolean;
  completed: boolean;
}) {
  return (
    <div
      className={`relative z-10 flex h-10 w-10 items-center justify-center rounded-full border-2 transition-all ${
        completed
          ? "bg-primary border-primary text-primary-foreground"
          : active
            ? "bg-background border-primary text-primary shadow-md"
            : "bg-background border-border text-muted-foreground"
      }`}
    >
      {completed ? (
        <CheckCircle2 className="size-5" />
      ) : (
        icon
      )}
    </div>
  );
}