import { useState } from "react";
import { useForm, Controller } from "react-hook-form";
import { useQuery } from "@tanstack/react-query";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import {
  ArrowRight,
  ArrowLeft,
  ChevronLeft,
  Truck,
  CheckCircle2,
  Loader2,
  UploadCloud,
} from "lucide-react";
import type { AuthUser } from "@/types/auth";
import type { CreateCompanyPayload } from "@/services/companies.service";
import {
  Button,
  Input,
  Field,
  FieldLabel,
  FieldError,
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
  SmartFileInput,
} from "@edr/ui-common";
import { cn } from "@/lib/utils";
import { api } from "@/services/api";

const TRUCK_TYPES = [
  "Casoni",
  "Truck Trailer",
  "High Bed",
  "Low Bed",
  "Others",
] as const;

type TransporterStep = "vehicle" | "documents" | "confirm";

const transporterSchema = z
  .object({
    tinNumber: z.string().length(10, "TIN must be exactly 10 digits"),
    fanNumber: z.string().length(16, "FAN must be exactly 16 digits"),
    truckType: z.string().min(1, "Truck type is required"),
    plateNumber: z.string().min(1, "Plate number is required"),
    plateNumber2: z.string().optional(),
    vehicleModel: z.string().min(1, "Vehicle model is required"),
    yearOfManufacturing: z
      .string()
      .min(1, "Year of manufacturing is required")
      .regex(/^\d{4}$/, "Enter a valid year (e.g. 2023)"),
  })
  .superRefine((data, ctx) => {
    if (
      data.truckType === "Casoni" &&
      (!data.plateNumber2 || data.plateNumber2.trim().length === 0)
    ) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        path: ["plateNumber2"],
        message: "Second plate number is required for Casoni",
      });
    }
  });

type FormData = z.infer<typeof transporterSchema>;

function buildPayload(data: FormData, user: AuthUser): CreateCompanyPayload {
  return {
    companyName: user.name?.en ?? "",
    companyEmail: user.email,
    companyPhone: user.phoneNumber,
    companyLocation: "",
    companyAddress: "",
    tin: data.tinNumber,
    vatNumber: "",
    fanNumber: data.fanNumber,
    attributes: {
      truckType: data.truckType,
      plateNumber: data.plateNumber,
      plateNumber2: data.plateNumber2 || null,
      vehicleModel: data.vehicleModel,
      yearOfManufacturing: data.yearOfManufacturing,
    },
  };
}

export default function TransporterForm({
  documentSettingCode,
  documentFiles: controlledFiles,
  onDocumentFilesChange,
  user,
  onSubmit,
  isPending,
  onBack,
}: {
  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;
}) {
  const [step, setStep] = useState<TransporterStep>("vehicle");
  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,
    handleSubmit,
    trigger,
    watch,
    control,
    formState: { errors },
  } = useForm<FormData>({
    resolver: zodResolver(transporterSchema),
    defaultValues: {
      tinNumber: "",
      fanNumber: "",
      truckType: "",
      plateNumber: "",
      plateNumber2: "",
      vehicleModel: "",
      yearOfManufacturing: "",
    },
  });

  const truckType = watch("truckType");
  const isCasoni = truckType === "Casoni";
  const formValues = watch();
  const hasDocuments = Boolean(uploadSetting?.fields?.length);
  const totalSteps = 3;

  const nextStep = async () => {
    if (step === "documents") {
      setStep("confirm");
      return;
    }
    if (step === "confirm") {
      handleSubmit((data) => onSubmit(buildPayload(data, user)))();
      return;
    }
    const fields: (keyof FormData)[] = [
      "tinNumber",
      "fanNumber",
      "truckType",
      "plateNumber",
      "vehicleModel",
      "yearOfManufacturing",
    ];
    const isValid = await trigger(fields);
    if (!isValid) return;
    setStep("documents");
  };

  const skipDocuments = () => {
    setStep("confirm");
  };

  const prevStep = () => {
    if (step === "vehicle") {
      onBack();
    } else if (step === "documents") {
      setStep("vehicle");
    } else {
      setStep("documents");
    }
  };

  return (
    <>
      <div className="mb-8">
        <button
          type="button"
          onClick={prevStep}
          className="mb-4 flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors"
        >
          <ChevronLeft className="size-4" />
          Change account type
        </button>

        <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={<Truck className="size-5" />}
            active={step === "vehicle"}
            completed={step !== "vehicle"}
          />
          <StepIcon
            icon={<UploadCloud className="size-5" />}
            active={step === "documents"}
            completed={step === "confirm"}
          />
          <StepIcon
            icon={<CheckCircle2 className="size-5" />}
            active={step === "confirm"}
            completed={false}
          />
        </div>
        <p className="text-center text-sm text-muted-foreground mt-3">
          {step === "vehicle" && `Step 1 of ${totalSteps} — Vehicle Information`}
          {step === "documents" && `Step 2 of ${totalSteps} — Upload Documents (Optional)`}
          {step === "confirm" && `Step 3 of ${totalSteps} — Review & Confirm`}
        </p>
      </div>

      <form
        onSubmit={(e) => e.preventDefault()}
        className="flex flex-col gap-4"
      >
        {step === "vehicle" && (
          <>
            <div className="grid grid-cols-2 gap-4">
              <Field data-invalid={Boolean(errors.tinNumber)}>
                <FieldLabel>TIN Number (10 digits)</FieldLabel>
                <Input
                  placeholder="1234567890"
                  maxLength={10}
                  aria-invalid={Boolean(errors.tinNumber)}
                  {...register("tinNumber")}
                />
                <FieldError errors={[errors.tinNumber]} />
              </Field>

              <Field data-invalid={Boolean(errors.fanNumber)}>
                <FieldLabel>FAN Number (16 digits)</FieldLabel>
                <Input
                  placeholder="1234567890123456"
                  maxLength={16}
                  aria-invalid={Boolean(errors.fanNumber)}
                  {...register("fanNumber")}
                />
                <FieldError errors={[errors.fanNumber]} />
              </Field>
            </div>

            <hr className="border-border" />

            <h3 className="text-sm font-semibold text-foreground">
              Vehicle / Truck Information
            </h3>

            <Controller
              name="truckType"
              control={control}
              render={({ field, fieldState }) => (
                <Field data-invalid={Boolean(fieldState.error)}>
                  <FieldLabel>Truck Type</FieldLabel>
                  <Select value={field.value} onValueChange={field.onChange}>
                    <SelectTrigger
                      className={cn(
                        "w-full",
                        fieldState.error ? "border-destructive!" : "",
                      )}
                      aria-invalid={Boolean(fieldState.error)}
                    >
                      <SelectValue placeholder="Select truck type..." />
                    </SelectTrigger>
                    <SelectContent>
                      {TRUCK_TYPES.map((type) => (
                        <SelectItem key={type} value={type}>
                          {type}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <FieldError errors={[fieldState.error]} />
                </Field>
              )}
            />

            <div className="grid grid-cols-2 gap-4">
              <Field data-invalid={Boolean(errors.plateNumber)}>
                <FieldLabel>Plate Number{isCasoni ? " (Front)" : ""}</FieldLabel>
                <Input
                  placeholder={isCasoni ? "AA-12345" : "AA-12345"}
                  aria-invalid={Boolean(errors.plateNumber)}
                  {...register("plateNumber")}
                />
                <FieldError errors={[errors.plateNumber]} />
              </Field>

              {isCasoni && (
                <Field data-invalid={Boolean(errors.plateNumber2)}>
                  <FieldLabel>Plate Number (Trailer)</FieldLabel>
                  <Input
                    placeholder="AA-67890"
                    aria-invalid={Boolean(errors.plateNumber2)}
                    {...register("plateNumber2")}
                  />
                  <FieldError errors={[errors.plateNumber2]} />
                </Field>
              )}

              {!isCasoni && (
                <Field data-invalid={Boolean(errors.vehicleModel)}>
                  <FieldLabel>Vehicle Model</FieldLabel>
                  <Input
                    placeholder="Isuzu FVR 2024"
                    aria-invalid={Boolean(errors.vehicleModel)}
                    {...register("vehicleModel")}
                  />
                  <FieldError errors={[errors.vehicleModel]} />
                </Field>
              )}
            </div>

            <div className="grid grid-cols-2 gap-4">
              {isCasoni && (
                <Field data-invalid={Boolean(errors.vehicleModel)}>
                  <FieldLabel>Vehicle Model</FieldLabel>
                  <Input
                    placeholder="Isuzu FVR 2024"
                    aria-invalid={Boolean(errors.vehicleModel)}
                    {...register("vehicleModel")}
                  />
                  <FieldError errors={[errors.vehicleModel]} />
                </Field>
              )}

              <Field data-invalid={Boolean(errors.yearOfManufacturing)}>
                <FieldLabel>Year of Manufacturing</FieldLabel>
                <Input
                  placeholder="2023"
                  maxLength={4}
                  aria-invalid={Boolean(errors.yearOfManufacturing)}
                  {...register("yearOfManufacturing")}
                />
                <FieldError errors={[errors.yearOfManufacturing]} />
              </Field>
            </div>
          </>
        )}

        {step === "documents" && (
          <>
            {loadingDocuments ? (
              <div className="flex items-center justify-center py-8">
                <Loader2 className="size-6 animate-spin text-muted-foreground" />
              </div>
            ) : !uploadSetting ? (
              <p className="text-sm text-muted-foreground text-center py-4">
                No document requirements found for your account type.
              </p>
            ) : (
              <div className="flex flex-col gap-6">
                <SmartFileInput
                  file={uploadSetting}
                  value={documentFiles}
                  onChange={setDocumentFiles}
                />
              </div>
            )}
          </>
        )}

        {step === "confirm" && (
          <div className="space-y-4 rounded-xl border border-border bg-card p-4">
            <div>
              <h3 className="text-base font-semibold text-foreground">
                Review your registration
              </h3>
              <p className="text-sm text-muted-foreground mt-1">
                Confirm the details below before saving.
              </p>
            </div>

            <div className="grid gap-3 md:grid-cols-2">
              <ReviewRow label="TIN Number" value={formValues.tinNumber} />
              <ReviewRow label="FAN Number" value={formValues.fanNumber} />
              <ReviewRow label="Truck Type" value={formValues.truckType} />
              <ReviewRow label="Plate Number" value={formValues.plateNumber} />
              {formValues.plateNumber2 && (
                <ReviewRow label="Plate (Trailer)" value={formValues.plateNumber2} />
              )}
              <ReviewRow label="Vehicle Model" value={formValues.vehicleModel} />
              <ReviewRow label="Year" value={formValues.yearOfManufacturing} />
            </div>
          </div>
        )}

        <div className="flex items-center justify-between pt-2">
          <Button type="button" variant="outline" onClick={prevStep}>
            <ArrowLeft />
            {step === "vehicle"
              ? "Change Type"
              : step === "confirm"
                ? "Back to Documents"
                : "Back"}
          </Button>

          <div className="flex items-center gap-3">
            {step === "documents" && (
              <Button
                type="button"
                variant="outline"
                onClick={skipDocuments}
                disabled={isPending}
              >
                Skip for now
              </Button>
            )}

            <Button
              type="button"
              onClick={step === "confirm" ? handleSubmit((data) => onSubmit(buildPayload(data, user))) : nextStep}
              disabled={isPending || (step === "documents" && !hasDocuments && loadingDocuments)}
            >
              {isPending ? (
                <>
                  <Loader2 className="animate-spin" />
                  Submitting...
                </>
              ) : step === "documents" ? (
                "Continue"
              ) : step === "confirm" ? (
                "Submit Registration"
              ) : (
                <>
                  Next Step
                  <ArrowRight />
                </>
              )}
            </Button>
          </div>
        </div>
      </form>
    </>
  );
}

function ReviewRow({ label, value }: { label: string; value?: string | null }) {
  return (
    <div className="rounded-lg border border-border bg-muted/20 p-3">
      <div className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
        {label}
      </div>
      <div className="mt-1 text-sm font-medium text-foreground">
        {value?.trim() ? value : "Not provided"}
      </div>
    </div>
  );
}

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>
  );
}
