import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import {
  ArrowRight,
  Eye,
  EyeOff,
  UserPlus,
  Loader2,
  Check,
  X,
} from "lucide-react";
import { userType } from "@/enums/userType";
import useAuth from "@/hooks/useAuth";
import type { SignupPayload } from "@/types/auth";
import AuthLayout from "@/components/auth/AuthLayout";
import PhoneInput from "@/components/auth/PhoneInput";
import { cn } from "@/lib/utils";
import {
  Button,
  Input,
  Field,
  FieldLabel,
  FieldError,
  FieldGroup,
} from "@edr/ui-common";

const passwordRequirements = [
  { label: "At least 8 characters", test: (v: string) => v.length >= 8 },
  { label: "One uppercase letter", test: (v: string) => /[A-Z]/.test(v) },
  { label: "One lowercase letter", test: (v: string) => /[a-z]/.test(v) },
  { label: "One number", test: (v: string) => /\d/.test(v) },
  {
    label: "One special character",
    test: (v: string) => /[^A-Za-z0-9]/.test(v),
  },
] as const;

const userSchema = z
  .object({
    email: z.string().email("Invalid email address"),
    countryCode: z.string().min(1, "Country code is required"),
    phone: z
      .string()
      .min(9, "Phone number is too short")
      .max(9, "Phone number is too long"),
    userType: z.string(),
    firstName: z.object({
      en: z.string().min(2, "Name is required"),
      am: z.string().nullable(),
    }),
    lastName: z.object({
      en: z.string().min(2, "Name is required"),
      am: z.string().nullable(),
    }),
    password: z
      .string()
      .min(8, "Password must be at least 8 characters")
      .regex(/[A-Z]/, "Password must include an uppercase letter")
      .regex(/[a-z]/, "Password must include a lowercase letter")
      .regex(/\d/, "Password must include a number")
      .regex(/[^A-Za-z0-9]/, "Password must include a special character"),
    confirmPassword: z.string().min(1, "Please confirm your password"),
  })
  .refine((data) => data.password === data.confirmPassword, {
    message: "Passwords do not match",
    path: ["confirmPassword"],
  });

type FormData = z.infer<typeof userSchema>;

export default function SignupPage() {
  const navigate = useNavigate();
  const { signup } = useAuth();
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);

  const {
    register,
    handleSubmit,
    watch,
    formState: { errors },
  } = useForm<FormData>({
    resolver: zodResolver(userSchema),
    defaultValues: {
      email: "",
      countryCode: "+251",
      phone: "",
      userType: userType.individual,
      firstName: { en: "", am: "" },
      lastName: { en: "", am: "" },
      password: "",
      confirmPassword: "",
    },
  });

  const onSubmit = async (data: FormData) => {
    setError(null);
    setLoading(true);
    try {
      const normalizedPhone = data.phone.startsWith("0")
        ? data.phone.slice(1)
        : data.phone;
      const payload: SignupPayload = {
        email: data.email,
        username: data.email,
        phoneNumber: `${data.countryCode}${normalizedPhone}`,
        userType: data.userType,
        name: {
          en: `${data.firstName.en} ${data.lastName.en}`,
          am: `${data.firstName.en} ${data.lastName.en}`,
        },
        password: data.password,
        confirmPassword: data.confirmPassword,
      };
      const result = await signup(payload);
      if (result.success) {
        navigate("/portal");
        // navigate("/otp");
      } else {
        setError(result.error.message);
      }
    } catch {
      setError("An unexpected error occurred");
    } finally {
      setLoading(false);
    }
  };

  return (
    <AuthLayout
      left={{
        badge: "Smart Freight Operations",
        title: "Create your freight operations account",
        description:
          "Join EDR Freight to manage shipments, monitor railway operations, track consignments, and streamline logistics workflows across Ethiopia and Djibouti.",
        features: [
          "Real-time shipment tracking",
          "Secure logistics management",
          "Enterprise-grade operations",
          "Multi-corridor freight monitoring",
        ],
        stats: {
          label: "Active Corridors",
          value: "24+",
          footer: "Operational",
          progress: "w-[95%]",
        },
      }}
    >
      <div className="mb-6">
        <div className="mb-4 flex size-12 items-center justify-center rounded-2xl bg-primary/10 text-primary">
          <UserPlus className="size-6" />
        </div>
        <h2 className="text-2xl font-black tracking-tight">Create Account</h2>
        <p className="mt-2 text-base text-muted-foreground">
          Register to access EDR Freight services.
        </p>
      </div>

      {error && (
        <div className="mb-4 rounded-xl border border-red-200 bg-red-50 px-4 py-2.5 text-sm text-red-700">
          {error}
        </div>
      )}

      <form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-4">
        <FieldGroup className="gap-4">
          <div className="flex gap-4">
            <Field data-invalid={Boolean(errors.firstName?.en)}>
              <FieldLabel>First Name</FieldLabel>
              <Input
                type="text"
                placeholder="John"
                disabled={loading}
                aria-invalid={Boolean(errors.firstName?.en)}
                {...register("firstName.en")}
              />
              <FieldError errors={[errors.firstName?.en]} />
            </Field>

            <Field data-invalid={Boolean(errors.lastName?.en)}>
              <FieldLabel>Last Name</FieldLabel>
              <Input
                type="text"
                placeholder="Doe"
                disabled={loading}
                aria-invalid={Boolean(errors.lastName?.en)}
                {...register("lastName.en")}
              />
              <FieldError errors={[errors.lastName?.en]} />
            </Field>
          </div>
          <Field data-invalid={Boolean(errors.email)}>
            <FieldLabel>Email Address</FieldLabel>
            <Input
              type="email"
              placeholder="john@example.com"
              disabled={loading}
              aria-invalid={Boolean(errors.email)}
              {...register("email")}
            />
            <FieldError errors={[errors.email]} />
          </Field>

          <PhoneInput
            disabled={loading}
            countryCode={{ ...register("countryCode") }}
            phone={{ ...register("phone") }}
            countryCodeError={errors.countryCode}
            phoneError={errors.phone}
          />

          <Field data-invalid={Boolean(errors.password)}>
            <FieldLabel>Password</FieldLabel>
            <div className="relative">
              <Input
                type={showPassword ? "text" : "password"}
                placeholder="Create a strong password"
                disabled={loading}
                aria-invalid={Boolean(errors.password)}
                className="pr-10"
                {...register("password")}
              />
              <button
                type="button"
                onClick={() => setShowPassword(!showPassword)}
                className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                tabIndex={-1}
              >
                {showPassword ? (
                  <EyeOff className="size-4" />
                ) : (
                  <Eye className="size-4" />
                )}
              </button>
            </div>
            <FieldError errors={[errors.password]} />
            <div className="mt-2 space-y-1">
              {passwordRequirements.map((req) => {
                const met = req.test(watch("password") ?? "");
                return (
                  <div
                    key={req.label}
                    className={cn(
                      "flex items-center gap-1.5 text-xs transition-colors",
                      met ? "text-emerald-600" : "text-muted-foreground",
                    )}
                  >
                    {met ? (
                      <Check className="size-3" />
                    ) : (
                      <X className="size-3" />
                    )}
                    {req.label}
                  </div>
                );
              })}
            </div>
          </Field>

          <Field data-invalid={Boolean(errors.confirmPassword)}>
            <FieldLabel>Confirm Password</FieldLabel>
            <div className="relative">
              <Input
                type={showConfirmPassword ? "text" : "password"}
                placeholder="Re-enter your password"
                disabled={loading}
                aria-invalid={Boolean(errors.confirmPassword)}
                className="pr-10"
                {...register("confirmPassword")}
              />
              <button
                type="button"
                onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                tabIndex={-1}
              >
                {showConfirmPassword ? (
                  <EyeOff className="size-4" />
                ) : (
                  <Eye className="size-4" />
                )}
              </button>
            </div>
            <FieldError errors={[errors.confirmPassword]} />
          </Field>
        </FieldGroup>

        <Button type="submit" disabled={loading} size="lg" className="w-full">
          {loading ? (
            <>
              <Loader2 className="animate-spin" data-icon="inline-start" />
              Creating...
            </>
          ) : (
            <>
              Create Account
              <ArrowRight data-icon="inline-end" />
            </>
          )}
        </Button>

        <p className="text-center text-sm text-muted-foreground">
          Already have an account?
          <Button
            type="button"
            variant="link"
            size="sm"
            onClick={() => navigate("/login")}
            className="h-auto p-0 font-semibold"
          >
            Sign In
          </Button>
        </p>
      </form>
    </AuthLayout>
  );
}
