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

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

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

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

type Step = "personal" | "transport";

const schema = z.object({
  // PERSONAL
  firstName: z.string().min(1),
  lastName: z.string().min(1),
  email: z.string().email(),
  phoneNumber: z
    .string()
    .min(1)
    .refine(isValidPhone, "Enter a valid phone number"),

  // TRANSPORT
  fanNumber: z.string().min(1),
  tinNumber: z.string().min(1),

  truckType: z.enum([
    "Casoni",
    "Truck Trailer",
    "High Bed",
    "Low Bed",
    "Others",
  ]),

  plateNumber: z.string().min(1),

  plateNumber2: z.string().optional(),

  vehicleModel: z.string().min(1),
  yearOfManufacturing: z.string().min(1),
});

type FormData = z.infer<typeof schema>;

const stepFields: Record<Step, (keyof FormData)[]> = {
  personal: [
    "firstName",
    "lastName",
    "email",
    "phoneNumber",
  ],
  transport: [
    "fanNumber",
    "tinNumber",
    "truckType",
    "plateNumber",
    "plateNumber2",
    "vehicleModel",
    "yearOfManufacturing",
  ],
};

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

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

  const truckType = watch("truckType");

  const nextStep = async () => {
    const valid = await trigger(stepFields[step]);
    if (!valid) return;

    if (step === "personal") setStep("transport");
    else handleSubmit(onSubmit)();
  };

  const prevStep = () => {
    if (step === "transport") setStep("personal");
  };

  const onSubmit = (data: FormData) => {
    console.log("TRANSPORTER:", data);
  };

  return (
    <>
      {/* STEPPER */}
      <div className="mb-8 lg:col-span-2">
        <div className="flex items-center justify-between max-w-lg 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={<Truck className="size-5" />}
            active={step === "transport"}
            completed={false}
          />
        </div>

        <p className="text-center text-sm text-muted-foreground mt-3">
          {step === "personal" && "Step 1 of 2 — Personal Information"}
          {step === "transport" && "Step 2 of 2 — Transport 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={!!errors.firstName}>
                  <FieldLabel>First Name</FieldLabel>
                  <Input {...register("firstName")} />
                  <FieldError errors={[errors.firstName]} />
                </Field>

                <Field data-invalid={!!errors.lastName}>
                  <FieldLabel>Last Name</FieldLabel>
                  <Input {...register("lastName")} />
                  <FieldError errors={[errors.lastName]} />
                </Field>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <Field data-invalid={!!errors.email}>
                  <FieldLabel>Email</FieldLabel>
                  <Input type="email" {...register("email")} />
                  <FieldError errors={[errors.email]} />
                </Field>

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

          {/* TRANSPORT */}
          {step === "transport" && (
            <>
              <div className="grid grid-cols-2 gap-4">
                <Field data-invalid={!!errors.fanNumber}>
                  <FieldLabel>FAN Number</FieldLabel>
                  <Input {...register("fanNumber")} />
                  <FieldError errors={[errors.fanNumber]} />
                </Field>

                <Field data-invalid={!!errors.tinNumber}>
                  <FieldLabel>TIN Number</FieldLabel>
                  <Input {...register("tinNumber")} />
                  <FieldError errors={[errors.tinNumber]} />
                </Field>
              </div>

              <Field data-invalid={!!errors.truckType}>
                <FieldLabel>Truck Type</FieldLabel>
                <select
                  className="w-full border rounded-md p-2 bg-background"
                  {...register("truckType")}
                >
                  <option value="">Select type</option>
                  <option value="Casoni">Casoni</option>
                  <option value="Truck Trailer">Truck Trailer</option>
                  <option value="High Bed">High Bed</option>
                  <option value="Low Bed">Low Bed</option>
                  <option value="Others">Others</option>
                </select>
                <FieldError errors={[errors.truckType]} />
              </Field>

              <div className="grid grid-cols-2 gap-4">
                <Field data-invalid={!!errors.plateNumber}>
                  <FieldLabel>Plate Number</FieldLabel>
                  <Input {...register("plateNumber")} />
                  <FieldError errors={[errors.plateNumber]} />
                </Field>

                {truckType === "Casoni" && (
                  <Field data-invalid={!!errors.plateNumber2}>
                    <FieldLabel>Second Plate Number (Casoni)</FieldLabel>
                    <Input {...register("plateNumber2")} />
                    <FieldError errors={[errors.plateNumber2]} />
                  </Field>
                )}
              </div>

              <div className="grid grid-cols-2 gap-4">
                <Field data-invalid={!!errors.vehicleModel}>
                  <FieldLabel>Vehicle Model</FieldLabel>
                  <Input {...register("vehicleModel")} />
                  <FieldError errors={[errors.vehicleModel]} />
                </Field>

                <Field data-invalid={!!errors.yearOfManufacturing}>
                  <FieldLabel>Year of Manufacturing</FieldLabel>
                  <Input {...register("yearOfManufacturing")} />
                  <FieldError errors={[errors.yearOfManufacturing]} />
                </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 === "transport" ? (
              "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>
  );
}