import { useState, useMemo } 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, Check, Eye, EyeOff, LockKeyhole, Loader2, X } from "lucide-react";
import useAuth from "@/hooks/useAuth";
import AuthLayout from "@/components/auth/AuthLayout";
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 passwordSchema = z
  .object({
    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 passwordSchema>;

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

  const {
    register,
    handleSubmit,
    watch,
    formState: { errors },
  } = useForm<FormData>({
    resolver: zodResolver(passwordSchema),
    defaultValues: { password: "", confirmPassword: "" },
  });

  const password = watch("password");

  const requirements = useMemo(
    () => passwordRequirements.map((r) => ({ ...r, met: r.test(password || "") })),
    [password],
  );

  const allMet = requirements.every((r) => r.met);

  const onSubmit = async (data: FormData) => {
    setError(null);
    setLoading(true);
    try {
      const result = await setPassword({
        newPassword: data.password,
        confirmPassword: data.confirmPassword,
      });
      if (result.success) {
        navigate("/auth");
      } else {
        setError(result.error.message);
      }
    } catch {
      setError("An unexpected error occurred");
    } finally {
      setLoading(false);
    }
  };

  return (
    <AuthLayout
      left={{
        badge: "Account Security",
        title: "Set your secure password",
        description:
          "Create a strong password to secure your EDR Freight account and protect railway logistics operations and shipment data.",
        features: [
          "Enterprise-grade security",
          "Protected account access",
          "Secure freight operations",
          "Advanced authentication system",
        ],
        stats: { label: "Security Protection", value: "256-bit", footer: "Encrypted", progress: "w-[98%]" },
      }}
    >
      <div className="mb-6">
        <div className="mb-4 flex size-12 items-center justify-center rounded-2xl bg-primary/10 text-primary">
          <LockKeyhole className="size-6" />
        </div>
        <h2 className="text-2xl font-black tracking-tight">Set Password</h2>
        <p className="mt-2 text-base text-muted-foreground">
          Create a secure password for your account.
        </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>
          <Field data-invalid={Boolean(errors.password)}>
            <FieldLabel>Password</FieldLabel>
            <div className="relative">
              <Input
                type={showPassword ? "text" : "password"}
                placeholder="Enter password"
                disabled={loading}
                aria-invalid={Boolean(errors.password)}
                className="pr-12"
                {...register("password")}
              />
              <Button
                type="button"
                variant="ghost"
                size="icon-sm"
                onClick={() => setShowPassword(!showPassword)}
                className="absolute right-1 top-1/2 -translate-y-1/2 text-muted-foreground"
              >
                {showPassword ? <EyeOff /> : <Eye />}
              </Button>
            </div>
            <FieldError errors={[errors.password]} />
          </Field>

          {password && (
            <ul className="space-y-1.5">
              {requirements.map((req) => (
                <li
                  key={req.label}
                  className={cn(
                    "flex items-center gap-2 text-sm",
                    req.met ? "text-emerald-600" : "text-muted-foreground",
                  )}
                >
                  {req.met ? (
                    <Check className="size-4 shrink-0 text-emerald-500" />
                  ) : (
                    <X className="size-4 shrink-0 text-muted-foreground/50" />
                  )}
                  {req.label}
                </li>
              ))}
            </ul>
          )}

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

        <Button
          type="submit"
          disabled={loading || !allMet}
          size="lg"
          className="w-full"
        >
          {loading ? (
            <>
              <Loader2 className="animate-spin" data-icon="inline-start" />
              Saving...
            </>
          ) : (
            <>
              Save Password
              <ArrowRight data-icon="inline-end" />
            </>
          )}
        </Button>
      </form>
    </AuthLayout>
  );
}
