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, MailCheck, RotateCw, Loader2 } from "lucide-react";
import { verificationCodeType } from "@/enums/verificationCodeType";
import useAuth from "@/hooks/useAuth";
import AuthLayout from "@/components/auth/AuthLayout";
import {
  Button,
  Input,
  Field,
  FieldLabel,
  FieldError,
  FieldGroup,
} from "@edr/ui-common";

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%]" },
      }}
    >
      <div className="mb-6">
        <div className="mb-4 flex size-12 items-center justify-center rounded-2xl bg-primary/10 text-primary">
          <MailCheck className="size-6" />
        </div>
        <h2 className="text-2xl font-black tracking-tight">OTP Verification</h2>
        <p className="mt-2 text-base text-muted-foreground">Enter the 6-digit code sent to:</p>
        <div className="mt-3 rounded-xl border border-border bg-muted/50 px-4 py-2">
          <p className="text-sm font-semibold">{maskedPhone}</p>
        </div>
      </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>
      )}

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

      <form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-4">
        <FieldGroup>
          <Field data-invalid={Boolean(errors.code)}>
            <FieldLabel>Verification Code</FieldLabel>
            <Input
              type="text"
              inputMode="numeric"
              autoComplete="one-time-code"
              maxLength={6}
              placeholder="123456"
              disabled={verifying}
              aria-invalid={Boolean(errors.code)}
              className="h-14 text-center text-2xl font-black tracking-[10px]"
              {...register("code")}
            />
            <div className="mt-1.5 flex items-center justify-between">
              {errors.code ? (
                <FieldError errors={[errors.code]} />
              ) : (
                <p className="text-xs text-muted-foreground">Enter the OTP sent to your phone</p>
              )}
              <span className="text-xs text-muted-foreground">{otpValue.length}/6</span>
            </div>
          </Field>
        </FieldGroup>

        <Button
          type="submit"
          disabled={verifying || otpValue.length !== 6}
          size="lg"
          className="w-full"
        >
          {verifying ? (
            <>
              <Loader2 className="animate-spin" data-icon="inline-start" />
              Verifying...
            </>
          ) : (
            <>
              Verify Account
              <ArrowRight data-icon="inline-end" />
            </>
          )}
        </Button>

        <Button
          type="button"
          variant="outline"
          onClick={handleResend}
          disabled={resending}
          className="w-full"
        >
          {resending ? (
            <>
              <Loader2 className="animate-spin" data-icon="inline-start" />
              Sending...
            </>
          ) : (
            <>
              <RotateCw data-icon="inline-start" />
              Resend Code
            </>
          )}
        </Button>

        <p className="text-center text-sm text-muted-foreground">
          Didn't receive the code?
          <Button
            type="button"
            variant="link"
            size="sm"
            onClick={handleResend}
            className="h-auto p-0 font-semibold"
          >
            Send again
          </Button>
        </p>
      </form>
    </AuthLayout>
  );
}
