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,
  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"
  | "representative";

const schema = 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 company email"),

  companyPhone: z
    .string()
    .min(1, "Company phone is required")
    .refine(isValidPhone, "Enter a valid phone number"),

  companyLocation: z
    .string()
    .min(1, "Company location is required"),

  companyAddress: z
    .string()
    .min(1, "Company address is required"),

  // REPRESENTATIVE
  representativeName: z
    .string()
    .min(1, "Representative name is required"),

  representativeEmail: z
    .string()
    .email("Invalid representative email"),

  representativePhone: z
    .string()
    .min(1, "Representative phone is required")
    .refine(isValidPhone, "Enter a valid phone number"),
});

type FormData = z.infer<typeof schema>;

const stepFields: Record<
  OnboardingStep,
  (keyof FormData)[]
> = {
  personal: [
    "firstName",
    "lastName",
    "email",
    "phoneNumber",
  ],

  company: [
    "companyName",
    "companyEmail",
    "companyPhone",
    "companyLocation",
    "companyAddress",
  ],

  representative: [
    "representativeName",
    "representativeEmail",
    "representativePhone",
  ],
};

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

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

    defaultValues: {
      phoneNumber: "",
      companyPhone: "",
      representativePhone: "",
    },
  });

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

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

    if (!isValid) return;

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

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

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

  return (
    <>
      {/* STEPPER */}
      <div className="mb-8">
        <div className="flex items-center justify-between max-w-xl 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 === "representative"
            }
          />

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

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

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

          {step === "representative" &&
            "Step 3 of 3 — Representative Information"}
        </p>
      </div>

      {/* FORM */}
      <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="Ahmed"
                    {...register("firstName")}
                  />

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

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

                  <Input
                    placeholder="Ali"
                    {...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="agent@company.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="Djibouti Freight Co."
                  {...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 / Country
                  </FieldLabel>

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

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

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

                  <Input
                    placeholder="Rue de Venise"
                    {...register(
                      "companyAddress"
                    )}
                  />

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

          {/* REPRESENTATIVE */}
          {step ===
            "representative" && (
            <>
              <Field
                data-invalid={Boolean(
                  errors.representativeName
                )}
              >
                <FieldLabel>
                  Company Representative Person
                  Name
                </FieldLabel>

                <Input
                  placeholder="Mohamed Hassan"
                  {...register(
                    "representativeName"
                  )}
                />

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

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

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

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

                <ControlledPhoneField
                  control={control}
                  name="representativePhone"
                  label="Representative Phone"
                  required
                />
              </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 === "representative" ? (
              "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>
  );
}