import { Alert, Box, Button, Stack, Text, TextInput } from "@mantine/core";
import { zodResolver } from "@hookform/resolvers/zod";
import { ArrowRight, MailCheck, RotateCw } from "lucide-react";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { useNavigate } from "react-router-dom";
import { z } from "zod";

import { verificationCodeType } from "@/enums/verificationCodeType";
import useAuth from "@/hooks/useAuth";
import AuthLayout from "@/components/auth/AuthLayout";

const otpSchema = z.object({
  code: z.string().regex(/^\d{6}$/, "OTP must be exactly 6 digits"),
});

type FormData = z.infer<typeof otpSchema>;

export default function VerificationOtpPage() {
  const navigate = useNavigate();
  const { verifyOTP, generateVerificationCode } = useAuth();
  const [verifying, setVerifying] = useState(false);
  const [resending, setResending] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [resentMessage, setResentMessage] = useState<string | null>(null);

  const phone = localStorage.getItem("otp-phone") || "";

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

  const otpValue = watch("code");

  const onSubmit = async (data: FormData) => {
    setError(null);
    setVerifying(true);
    try {
      const result = await verifyOTP(data.code);
      if (result.success) {
        navigate("/set-password");
      } else {
        setError(result.error.message);
      }
    } catch {
      setError("An unexpected error occurred");
    } finally {
      setVerifying(false);
    }
  };

  const handleResend = async () => {
    setResentMessage(null);
    setResending(true);
    try {
      const result = await generateVerificationCode(verificationCodeType.setPassword);
      if (result.success) {
        setResentMessage("New OTP code sent successfully.");
      } else {
        setError(result.error.message);
      }
    } catch {
      setError("An unexpected error occurred");
    } finally {
      setResending(false);
    }
  };

  const maskedPhone = phone.length > 4 ? `${phone.slice(0, 7)}******` : phone;

  return (
    <AuthLayout
      left={{
        badge: "Secure Verification",
        title: "Verify your account securely",
        description:
          "Enter the verification code sent to your phone number to continue using EDR Freight logistics services.",
        features: [
          "Secure OTP verification",
          "Protected account access",
          "Fast identity confirmation",
          "Enterprise-grade security",
        ],
        stats: { label: "Verification Security", value: "99.9%", footer: "Protected", progress: "w-[99%]" },
      }}
    >
      <Stack gap="xs" mb="lg">
        <Box w={48} h={48} bg="edr-soft" className="flex items-center justify-center rounded-2xl">
          <MailCheck size={22} color="var(--mantine-color-edr-green-6)" />
        </Box>
        <Box>
          <Text fz={24} fw={800} c="edr-text" className="tracking-tight">
            OTP Verification
          </Text>
          <Text fz={15} c="edr-muted" mt={4}>
            Enter the 6-digit code sent to:
          </Text>
          <Box mt={8} p={12} bg="edr-slate-soft" className="rounded-xl border border-edr-border">
            <Text size="sm" fw={600} c="edr-text">{maskedPhone}</Text>
          </Box>
        </Box>
      </Stack>

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

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

      <form onSubmit={handleSubmit(onSubmit)}>
        <Stack gap="md">
          <Box>
            <TextInput
              label="Verification Code"
              inputMode="numeric"
              autoComplete="one-time-code"
              maxLength={6}
              placeholder="123456"
              disabled={verifying}
              error={errors.code?.message}
              styles={{
                input: {
                  textAlign: "center",
                  fontSize: "24px",
                  fontWeight: 800,
                  letterSpacing: "10px",
                  height: "56px",
                },
              }}
              {...register("code")}
            />
            <Text size="xs" c="edr-muted" ta="right" mt={4}>
              {otpValue.length}/6
            </Text>
          </Box>

          <Button
            type="submit"
            disabled={verifying || otpValue.length !== 6}
            loading={verifying}
            size="lg"
            color="edr-green"
            fullWidth
            rightSection={!verifying ? <ArrowRight size={18} /> : undefined}
          >
            Verify Account
          </Button>

          <Button
            type="button"
            variant="outline"
            onClick={handleResend}
            disabled={resending}
            loading={resending}
            fullWidth
            leftSection={!resending ? <RotateCw size={16} /> : undefined}
          >
            Resend Code
          </Button>

          <Text size="sm" c="edr-muted" ta="center">
            Didn't receive the code?{" "}
            <Button
              variant="transparent"
              p={0}
              h="auto"
              c="edr-green.6"
              fw={600}
              fz="sm"
              onClick={handleResend}
            >
              Send again
            </Button>
          </Text>
        </Stack>
      </form>
    </AuthLayout>
  );
}
