'use client';

import { useEffect, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useGet } from '@/hooks/use-get';
import { useFormSubmission } from '@/hooks/use-form-submission';
import { toast } from '@/hooks/use-toast';
import { useTranslations } from 'next-intl';
import { USER_TOKEN_CL } from '@/utils/data/user-client';
import { Loader } from 'lucide-react';
import { EmailVerificationPrompt } from '@/components/app/email-verification-prompt';
import { EmailVerificationOTP } from '@/components/app/email-verification-otp';

export default function EmailVerifyPage() {
    const t = useTranslations();
    const router = useRouter();
    const searchParams = useSearchParams();
    const [showPrompt, setShowPrompt] = useState(false);
    const [showOTP, setShowOTP] = useState(false);

    // Guard: if no token, go to login
    useEffect(() => {
        const token = USER_TOKEN_CL();
        if (!token) {
            router.push('/login');
        }
    }, [router]);

    const { data: userData, isLoading, refetch } = useGet({
        url: '/user',
        context: 'dashboard',
        props: {
            enabled: true,
            refetchOnWindowFocus: false,
        }
    });

    // If already verified → skip directly to destination
    useEffect(() => {
        if (userData && !isLoading) {
            if (userData.is_verified === true) {
                const redirect = searchParams.get('redirect');
                router.push(redirect || '/dashboard');
            } else {
                // Not verified → show the prompt first
                setShowPrompt(true);
            }
        }
    }, [userData, isLoading, router, searchParams]);

    // Send code only when user clicks verify in the prompt
    const sendCode = useFormSubmission({
        endPoint: '/email/conifrm',
        method: 'POST',
        context: 'main',
        onSuccess: (response) => {
            toast({
                variant: 'success',
                title: t('custom.done'),
                description: response.message || t('custom.code-sent'),
            });
            setShowOTP(true);
        },
        onError: (error) => {
            const msg = error?.response?.data?.error || error?.response?.data?.message || t('custom.try-again');
            toast({ variant: 'destructive', title: t('custom.failed'), description: msg });
            // Re-show prompt so user can try again
            setShowPrompt(true);
            return { handled: true };
        },
    });

    const handleVerifyClick = () => {
        setShowPrompt(false);
        sendCode.mutate({});
    };

    // Cancel is not allowed — re-show prompt immediately
    const handleCancelPrompt = () => {
        setShowPrompt(true);
    };

    const handleOTPSuccess = () => {
        setShowOTP(false);
        refetch(); // refetch triggers "already verified" useEffect → redirect
    };

    // Close OTP is not allowed — re-show prompt
    const handleCloseOTP = () => {
        setShowOTP(false);
        setShowPrompt(true);
    };

    return (
        <main className="min-h-dvh flex flex-col items-center justify-center bg-gradient-to-br from-white to-blue-50">
            <div className="flex flex-col items-center gap-4 text-center px-4">
                <Loader className="w-10 h-10 animate-spin text-primary-tw-400" />
                <p className="text-gray-600 text-lg font-medium">
                    {t('custom.verifying')}...
                </p>
            </div>

            {/* Step 1: Prompt — user must click verify */}
            <EmailVerificationPrompt
                open={showPrompt}
                onVerify={handleVerifyClick}
                onCancel={handleCancelPrompt}
            />

            {/* Step 2: OTP — appears after code is sent */}
            <EmailVerificationOTP
                open={showOTP}
                onSuccess={handleOTPSuccess}
                onClose={handleCloseOTP}
            />
        </main>
    );
}
