'use client';

import { useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useVerifyEmail, useResendVerification, useLogout } from '@/hooks/useAuth';
import { useAuthStore } from '@/stores/authStore';
import Image from 'next/image';

export default function VerifyEmailPage() {
    const [code, setCode] = useState('');
    const [error, setError] = useState('');
    const [success, setSuccess] = useState('');
    const [isVerifying, setIsVerifying] = useState(false);

    const router = useRouter();
    const searchParams = useSearchParams();

    const email = searchParams.get('email') || useAuthStore.getState().user?.email;
    const { mutate: verifyEmail, isLoading } = useVerifyEmail();
    const { mutate: resendVerification, isLoading: isResending } = useResendVerification();
    const { mutate: logout } = useLogout();

    const handleSubmit = (e) => {
        e.preventDefault();
        setError('');
        setSuccess('');
        setIsVerifying(true);

        if (!email) {
            setError('Email address is required');
            setIsVerifying(false);
            return;
        }

        verifyEmail(
            { email, code },
            {
                onSuccess: () => {
                    setSuccess('Email verified successfully! Please log in to continue.');
                    setTimeout(() => {
                        logout();                // Clear auth state
                        router.push('/login');   // Redirect to login
                    }, 2000);
                },
                onError: (err) => {
                    setError(err.message || 'Verification failed');
                },
                onSettled: () => {
                    setIsVerifying(false);
                },
            }
        );
    };

    const handleLogout = () => {
        logout();
        router.push('/');
    };

    return (
        <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 to-blue-100">
            <form onSubmit={handleSubmit} className="bg-white p-8 rounded shadow-md w-full max-w-md">
                <div className="text-center space-y-6">
                    {error && (
                        <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">{error}</div>
                    )}
                    {success && (
                        <div className="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded">
                            {success}
                        </div>
                    )}
                    <div className="text-2xl font-bold text-blue-900">Verify Email</div>
                    <p className="text-sm text-blue-800">Check your inbox and enter the 6-digit code below.</p>
                    <div className="flex justify-center">
                        <Image src="/images/mail-icon.png" alt="Mail Icon" width={64} height={64} />
                    </div>

                    <p className="text-sm text-blue-900">
                        Verification code sent to:
                        <br />
                        <span className="font-semibold">{email}</span>
                    </p>

                    <input
                        type="text"
                        value={code}
                        onChange={(e) => setCode(e.target.value)}
                        placeholder="Enter confirmation code"
                        className="w-full px-4 py-3 border border-blue-200 rounded-lg text-center font-semibold tracking-widest text-gray-700"
                        maxLength={6}
                        required
                    />

                    <button
                        type="submit"
                        className="w-full py-3 bg-blue-800 text-white font-bold rounded-lg flex items-center justify-center"
                        disabled={isVerifying || isLoading}
                    >
                        {(isVerifying || isLoading) ? (
                            <svg
                                className="animate-spin h-5 w-5 text-white"
                                xmlns="http://www.w3.org/2000/svg"
                                fill="none"
                                viewBox="0 0 24 24"
                            >
                                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8z" />
                            </svg>
                        ) : (
                            'Verify'
                        )}
                    </button>

                    <div className="text-sm text-blue-700 mt-2">
                        <button
                            type="button"
                            onClick={() => {
                                if (!email) {
                                    setError('Email address is required to resend code');
                                    return;
                                }

                                resendVerification(
                                    { email },
                                    {
                                        onSuccess: () => {
                                            setSuccess('Verification code resent successfully');
                                            setError('');
                                        },
                                        onError: (err) => {
                                            setError(err.message || 'Failed to resend verification code');
                                        },
                                    }
                                );
                            }}
                            disabled={isResending}
                            className="underline mr-4 text-blue-700"
                        >
                            {isResending ? 'Resending...' : 'Resend code'}
                        </button>

                        <button type="button" onClick={handleLogout} className="underline text-blue-700">
                            Logout
                        </button>
                    </div>
                </div>
            </form>
        </div>
    );
}
