"use client";

import { Suspense } from "react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { useState, useEffect, useCallback } from "react";
import { Loader2 } from "lucide-react";

import { Button } from "@/components/ui/button";
import { AuthFormWrapper } from "@/components/forms/auth-form-wrapper";
import { CodeInput } from "@/components/forms/code-input";
import * as authApi from "@/lib/api/auth";
import { ApiError } from "@/lib/api/client";

const RESEND_COOLDOWN_SECONDS = 60;

function VerifyEmailForm() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const email = searchParams.get("email") ?? "";

  const [code, setCode] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isResending, setIsResending] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [cooldown, setCooldown] = useState(0);

  // Cooldown timer for resend button
  useEffect(() => {
    if (cooldown <= 0) return;
    const timer = setInterval(() => {
      setCooldown((c) => c - 1);
    }, 1000);
    return () => clearInterval(timer);
  }, [cooldown]);

  const handleSubmit = useCallback(
    async (submittedCode: string) => {
      if (submittedCode.length !== 6 || isSubmitting) return;
      setError(null);
      setIsSubmitting(true);
      try {
        await authApi.verifyEmail({ code: submittedCode });
        router.push("/login");
      } catch (err) {
        const message =
          err instanceof ApiError
            ? err.message
            : "Verification failed. Please try again.";
        setError(message);
      } finally {
        setIsSubmitting(false);
      }
    },
    [isSubmitting, router]
  );

  function handleCodeChange(newCode: string) {
    setCode(newCode);
    // Auto-submit when all 6 digits are entered
    if (newCode.length === 6) {
      handleSubmit(newCode);
    }
  }

  async function handleResend() {
    setIsResending(true);
    setError(null);
    try {
      await authApi.resendVerification();
      setCooldown(RESEND_COOLDOWN_SECONDS);
    } catch (err) {
      const message =
        err instanceof ApiError
          ? err.message
          : "Failed to resend code. Please try again.";
      setError(message);
    } finally {
      setIsResending(false);
    }
  }

  return (
    <AuthFormWrapper
      title="Verify your email"
      subtitle={
        email
          ? `Enter the 6-digit code sent to ${email}`
          : "Enter the 6-digit code sent to your email"
      }
      footer={
        <p>
          <Link href="/login" className="text-primary hover:underline">
            Back to login
          </Link>
        </p>
      }
    >
      <div className="flex flex-col gap-6">
        {error && (
          <div className="rounded-md bg-destructive/10 px-3 py-2 text-sm text-destructive">
            {error}
          </div>
        )}

        <CodeInput
          value={code}
          onChange={handleCodeChange}
          disabled={isSubmitting}
        />

        <Button
          type="button"
          className="w-full"
          disabled={code.length !== 6 || isSubmitting}
          onClick={() => handleSubmit(code)}
        >
          {isSubmitting && <Loader2 className="animate-spin" />}
          Verify email
        </Button>

        <div className="text-center">
          <Button
            type="button"
            variant="ghost"
            size="sm"
            disabled={isResending || cooldown > 0}
            onClick={handleResend}
          >
            {isResending && <Loader2 className="animate-spin" />}
            {cooldown > 0
              ? `Resend code (${cooldown}s)`
              : "Resend code"}
          </Button>
        </div>
      </div>
    </AuthFormWrapper>
  );
}

export default function VerifyEmailPage() {
  return (
    <Suspense>
      <VerifyEmailForm />
    </Suspense>
  );
}
