import { Alert, Box, Button, Group, PasswordInput, Stack, Text, ThemeIcon } from "@mantine/core";
import { zodResolver } from "@hookform/resolvers/zod";
import { ArrowRight, Check, LockKeyhole, X } from "lucide-react";
import { useMemo, useState } from "react";
import { useForm } from "react-hook-form";
import { useNavigate } from "react-router-dom";
import { z } from "zod";

import useAuth from "@/hooks/useAuth";
import AuthLayout from "@/components/auth/AuthLayout";

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 [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%]" },
      }}
    >
      <Stack gap="xs" mb="lg">
        <Box w={48} h={48} bg="edr-soft" className="flex items-center justify-center rounded-2xl">
          <LockKeyhole size={22} color="var(--mantine-color-edr-green-6)" />
        </Box>
        <Box>
          <Text fz={24} fw={800} c="edr-text" className="tracking-tight">
            Set Password
          </Text>
          <Text fz={15} c="edr-muted" mt={4}>
            Create a secure password for your account.
          </Text>
        </Box>
      </Stack>

      {error && (
        <Alert color="red" variant="light" radius="md" mb="md">
          {error}
        </Alert>
      )}

      <form onSubmit={handleSubmit(onSubmit)}>
        <Stack gap="md">
          <Box>
            <PasswordInput
              label="Password"
              placeholder="Enter password"
              disabled={loading}
              error={errors.password?.message}
              {...register("password")}
            />
            {password && (
              <Stack gap={4} mt={8}>
                {requirements.map((req) => (
                  <Group key={req.label} gap={6} align="center" wrap="nowrap">
                    <ThemeIcon
                      size={16}
                      radius="xl"
                      variant={req.met ? "filled" : "light"}
                      color={req.met ? "edr-green" : "gray"}
                    >
                      {req.met ? <Check size={10} /> : <X size={10} />}
                    </ThemeIcon>
                    <Text size="xs" c={req.met ? "edr-green.7" : "edr-muted"}>
                      {req.label}
                    </Text>
                  </Group>
                ))}
              </Stack>
            )}
          </Box>

          <PasswordInput
            label="Confirm Password"
            placeholder="Confirm password"
            disabled={loading}
            error={errors.confirmPassword?.message}
            {...register("confirmPassword")}
          />

          <Button
            type="submit"
            disabled={loading || !allMet}
            loading={loading}
            size="lg"
            color="edr-green"
            fullWidth
            rightSection={!loading ? <ArrowRight size={18} /> : undefined}
          >
            Save Password
          </Button>
        </Stack>
      </form>
    </AuthLayout>
  );
}
