import { useCallback, useEffect, useRef, useState } from "react";
import { Link, useNavigate, useSearchParams } from "react-router-dom";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { InputOTP, InputOTPGroup, InputOTPSlot } from "@/components/ui/input-otp";
import { GraduationCap, Loader2 } from "lucide-react";
import { useResendOtp, useVerifyEmail } from "@/hooks/queries/useSignup";
import { ApiError } from "@/lib/api-client";

const RESEND_LIMIT = 3;
const COOLDOWN_SEC = 60;

function errorMessage(err: unknown): string {
  if (err instanceof ApiError) return err.message;
  if (err instanceof Error) return err.message;
  return "Verification failed";
}

export default function EmailVerification() {
  const [searchParams] = useSearchParams();
  const email = searchParams.get("email")?.trim() || "";
  const navigate = useNavigate();
  const verify = useVerifyEmail();
  const resend = useResendOtp();
  const [otp, setOtp] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [resendAttempts, setResendAttempts] = useState(0);
  const [cooldown, setCooldown] = useState(0);
  const submittingRef = useRef(false);
  const lastSubmittedOtp = useRef<string | null>(null);

  useEffect(() => {
    if (otp.length < 6) lastSubmittedOtp.current = null;
  }, [otp]);

  useEffect(() => {
    if (cooldown <= 0) return;
    const t = window.setInterval(() => {
      setCooldown((c) => (c <= 1 ? 0 : c - 1));
    }, 1000);
    return () => window.clearInterval(t);
  }, [cooldown]);

  const runVerify = useCallback(
    async (code: string) => {
      if (!email || code.length !== 6) return;
      setError(null);
      submittingRef.current = true;
      try {
        await verify.mutateAsync({ email, otp: code });
        navigate("/onboarding", { replace: true });
      } catch (e) {
        lastSubmittedOtp.current = null;
        setError(errorMessage(e));
      } finally {
        submittingRef.current = false;
      }
    },
    [email, navigate, verify],
  );

  useEffect(() => {
    if (otp.length !== 6 || submittingRef.current || verify.isPending) return;
    if (lastSubmittedOtp.current === otp) return;
    lastSubmittedOtp.current = otp;
    void runVerify(otp);
  }, [otp, runVerify, verify.isPending]);

  const handleResend = async () => {
    if (!email || cooldown > 0 || resendAttempts >= RESEND_LIMIT || resend.isPending) return;
    setError(null);
    try {
      await resend.mutateAsync(email);
      setResendAttempts((n) => n + 1);
      setCooldown(COOLDOWN_SEC);
    } catch (e) {
      setError(errorMessage(e));
    }
  };

  if (!email) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gradient-to-b from-muted/40 to-background p-4">
        <Card className="w-full max-w-md border-0 shadow-lg">
          <CardHeader className="text-center">
            <CardTitle>Missing email</CardTitle>
            <CardDescription>Add an email query parameter or return to registration.</CardDescription>
          </CardHeader>
          <CardContent className="flex justify-center">
            <Button asChild variant="outline">
              <Link to="/register">Back to registration</Link>
            </Button>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-b from-muted/40 to-background p-4">
      <div className="w-full max-w-md space-y-8">
        <div className="flex items-center justify-center gap-2">
          <div className="h-10 w-10 rounded-xl bg-primary flex items-center justify-center shadow-sm">
            <GraduationCap className="h-6 w-6 text-primary-foreground" />
          </div>
          <h1 className="text-2xl font-bold tracking-tight">Verify your email</h1>
        </div>

        <Card className="border-0 shadow-xl bg-card/80 backdrop-blur-sm">
          <CardHeader className="text-center space-y-2">
            <CardTitle className="text-lg">Check your inbox</CardTitle>
            <CardDescription className="text-base leading-relaxed">
              We&apos;ve sent a 6-digit verification code to{" "}
              <span className="font-medium text-foreground">{email}</span>
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="flex flex-col items-center gap-4">
              <InputOTP maxLength={6} value={otp} onChange={setOtp} disabled={verify.isPending}>
                <InputOTPGroup>
                  <InputOTPSlot index={0} />
                  <InputOTPSlot index={1} />
                  <InputOTPSlot index={2} />
                  <InputOTPSlot index={3} />
                  <InputOTPSlot index={4} />
                  <InputOTPSlot index={5} />
                </InputOTPGroup>
              </InputOTP>
              {verify.isPending && (
                <div className="flex items-center gap-2 text-sm text-muted-foreground">
                  <Loader2 className="h-4 w-4 animate-spin" />
                  Verifying…
                </div>
              )}
            </div>

            {error && (
              <p className="text-center text-sm text-destructive bg-destructive/10 rounded-md py-2 px-3">{error}</p>
            )}

            <Button
              className="w-full"
              size="lg"
              onClick={() => void runVerify(otp)}
              disabled={otp.length !== 6 || verify.isPending}
            >
              {verify.isPending ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Verifying
                </>
              ) : (
                "Verify"
              )}
            </Button>

            <div className="text-center text-sm space-y-2">
              <p className="text-muted-foreground">
                Resend attempts:{" "}
                <span className="font-medium text-foreground">
                  {resendAttempts}/{RESEND_LIMIT}
                </span>
              </p>
              <button
                type="button"
                onClick={() => void handleResend()}
                disabled={cooldown > 0 || resendAttempts >= RESEND_LIMIT || resend.isPending}
                className="text-primary font-medium hover:underline disabled:opacity-50 disabled:no-underline"
              >
                {resend.isPending ? (
                  "Sending…"
                ) : cooldown > 0 ? (
                  `Resend code in ${cooldown}s`
                ) : (
                  "Resend code"
                )}
              </button>
            </div>

            <p className="text-center text-sm text-muted-foreground">
              Wrong address?{" "}
              <Link to="/register" className="text-primary font-medium hover:underline">
                Change email
              </Link>
            </p>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
