import React, { useState, useEffect } from 'react';
import { Head, Link, router } from '@inertiajs/react';
import axios from 'axios';
import { toast } from 'sonner';
import { 
    ShieldCheck, 
    CheckCircle, 
    ArrowLeft, 
    MailCheck,
    Loader2,
    RefreshCw,
    KeyRound
} from 'lucide-react';

export default function VerifyEmail({ email }) {
    const [otp, setOtp] = useState('');
    const [loading, setLoading] = useState(false);
    const [resending, setResending] = useState(false);
    const [errors, setErrors] = useState({});
    
    // Cooldown timer state for resending OTP (60s)
    const [cooldown, setCooldown] = useState(60);

    useEffect(() => {
        let timer;
        if (cooldown > 0) {
            timer = setTimeout(() => setCooldown(cooldown - 1), 1000);
        }
        return () => clearTimeout(timer);
    }, [cooldown]);

    const handleOtpChange = (e) => {
        const val = e.target.value.replace(/[^0-9]/g, '').slice(0, 6);
        setOtp(val);
        if (errors.otp) {
            setErrors({});
        }
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        if (otp.length !== 6) {
            setErrors({ otp: 'Please enter all 6 digits of the code.' });
            return;
        }

        setLoading(true);
        setErrors({});

        try {
            const response = await axios.post('/employer/verify-email', { otp });
            toast.success('Email verified successfully! Let\'s secure your account.');
            router.visit('/employer/create-password');
        } catch (err) {
            if (err.response) {
                if (err.response.status === 422 || err.response.status === 400) {
                    const otpErr = err.response.data?.errors?.otp || err.response.data?.message || 'Verification failed.';
                    setErrors({ otp: otpErr });
                    toast.error(otpErr);
                } else if (err.response.status === 429) {
                    toast.error('Too many requests. Please slow down.');
                } else {
                    toast.error('Failed to verify OTP. Please try again.');
                }
            } else {
                toast.error('Network error. Please check your connection.');
            }
        } finally {
            setLoading(false);
        }
    };

    const handleResend = async () => {
        if (cooldown > 0 || resending) return;

        setResending(true);
        try {
            const response = await axios.post('/employer/resend-otp');
            toast.success('A new verification code has been dispatched to your email.');
            setCooldown(60); // Reset timer
            setOtp('');
        } catch (err) {
            if (err.response) {
                toast.error(err.response.data?.message || 'Failed to dispatch verification code.');
                if (err.response.status === 429) {
                    setCooldown(60); // Reset cooldown on too many requests
                }
            } else {
                toast.error('Network error. Please check your connection.');
            }
        } finally {
            setResending(false);
        }
    };

    const renderStepIndicator = () => (
        <div className="flex items-center justify-between mb-12 relative max-w-md mx-auto px-4 select-none">
            <div className="absolute top-1/2 left-0 w-full h-0.5 bg-slate-100 -translate-y-1/2 -z-10" />
            <div className="absolute top-1/2 left-0 h-0.5 bg-[#185FA5] -translate-y-1/2 -z-10 transition-all duration-500" style={{ width: '50%' }} />
            
            {[
                { step: 1, label: 'Register' },
                { step: 2, label: 'Verify Code' },
                { step: 3, label: 'Set Password' }
            ].map((s) => (
                <div key={s.step} className="flex flex-col items-center">
                    <div className={`w-10 h-10 rounded-full flex items-center justify-center font-black text-sm border-4 transition-all duration-300 ${
                        s.step <= 2 
                            ? 'bg-[#185FA5] text-white border-blue-100 scale-110 shadow-lg' 
                            : 'bg-white text-slate-400 border-slate-50'
                    }`}>
                        {s.step}
                    </div>
                    <span className={`text-[9px] font-black uppercase mt-2 tracking-wider ${
                        s.step <= 2 ? 'text-[#185FA5]' : 'text-slate-400'
                    }`}>{s.label}</span>
                </div>
            ))}
        </div>
    );

    return (
        <div className="min-h-screen grid grid-cols-1 lg:grid-cols-12 bg-[#F8FAFC] font-sans selection:bg-blue-100 selection:text-[#185FA5]">
            <Head title="Verify Email - Step 2" />

            {/* Left Brand Panel */}
            <div className="hidden lg:flex lg:col-span-4 bg-[#185FA5] p-16 flex-col justify-between text-white relative overflow-hidden select-none sticky top-0 h-screen">
                <div className="absolute inset-0 bg-[radial-gradient(circle_at_top_right,rgba(255,255,255,0.1),transparent)] pointer-events-none" />
                
                <div className="relative z-10 space-y-10">
                    <div className="flex items-center space-x-4">
                        <div className="w-12 h-12 bg-white text-[#185FA5] rounded-2xl flex items-center justify-center font-black text-2xl shadow-2xl">
                            M
                        </div>
                        <span className="font-black text-2xl tracking-tighter uppercase">Marketplace</span>
                    </div>

                    <div className="space-y-6 pt-10">
                        <h1 className="text-5xl font-black tracking-tighter leading-[1.1] drop-shadow-sm uppercase">
                            Verify Your Business Email.
                        </h1>
                        <p className="text-blue-100 text-lg font-medium leading-relaxed opacity-90">
                            We take platform trust seriously. Verify your email to ensure secure account setup.
                        </p>
                    </div>
                </div>

                <div className="relative z-10 text-[10px] font-black uppercase tracking-[0.3em] text-blue-300 opacity-60">
                    Empowering Household Recruitment Since 2024
                </div>
            </div>

            {/* Right Form Content */}
            <div className="col-span-1 lg:col-span-8 flex flex-col items-center py-12 px-6 sm:px-12 overflow-y-auto justify-center">
                <div className="w-full max-w-xl">
                    <div className="text-center mb-10">
                        <h2 className="text-3xl font-black text-slate-900 tracking-tight uppercase">Email Verification</h2>
                        <p className="text-sm font-bold text-slate-400 mt-2 uppercase tracking-widest">
                            Step 2 of 3: Enter Hashed Passcode
                        </p>
                    </div>

                    {renderStepIndicator()}

                    <div className="bg-white rounded-[40px] shadow-[0_20px_50px_rgba(0,0,0,0.04)] border border-slate-100 p-8 sm:p-12 transition-all duration-500 animate-in fade-in slide-in-from-bottom-4">
                        
                        <div className="text-center mb-8">
                            <div className="w-16 h-16 bg-blue-50 text-[#185FA5] rounded-3xl flex items-center justify-center mx-auto mb-4 border border-blue-100 shadow-sm animate-pulse">
                                <MailCheck className="w-8 h-8" />
                            </div>
                            <h3 className="text-lg font-black text-slate-900 uppercase">Check Your Email</h3>
                            <p className="text-xs font-bold text-slate-400 mt-1 leading-relaxed">
                                We dispatched a 6-digit confirmation code to:
                                <br />
                                <span className="text-slate-800 font-extrabold lowercase text-sm mt-1 inline-block">{email}</span>
                            </p>
                        </div>

                        <form onSubmit={handleSubmit} className="space-y-6">
                            
                            <div className="space-y-3">
                                <label className="text-[10px] font-black text-slate-500 uppercase tracking-widest ml-1 text-center block">6-Digit Passcode</label>
                                <div className="relative max-w-xs mx-auto group">
                                    <KeyRound className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400 group-focus-within:text-[#185FA5] transition-colors" />
                                    <input
                                        type="text"
                                        pattern="[0-9]*"
                                        inputMode="numeric"
                                        maxLength="6"
                                        value={otp}
                                        onChange={handleOtpChange}
                                        placeholder="••••••"
                                        className={`w-full pl-12 pr-4 py-5 bg-slate-50 border rounded-2xl text-center text-2xl font-black tracking-[0.25em] focus:ring-4 focus:ring-blue-100 focus:bg-white transition-all outline-none ${
                                            errors.otp ? 'border-rose-400 bg-rose-50/20' : 'border-transparent'
                                        }`}
                                        required
                                    />
                                </div>
                                {errors.otp && (
                                    <p className="text-xs text-rose-500 font-bold text-center uppercase tracking-wider">{errors.otp}</p>
                                )}
                            </div>

                            <button
                                type="submit"
                                disabled={loading || otp.length !== 6}
                                className="w-full bg-[#185FA5] hover:bg-[#144f8a] disabled:opacity-70 text-white py-5 rounded-[24px] font-black text-xs uppercase tracking-[0.2em] transition-all shadow-xl shadow-blue-500/20 flex items-center justify-center space-x-2 mt-8 select-none cursor-pointer"
                            >
                                {loading ? (
                                    <>
                                        <Loader2 className="w-5 h-5 animate-spin mr-2" />
                                        <span>Verifying Code...</span>
                                    </>
                                ) : (
                                    <>
                                        <span>Confirm Verification</span>
                                        <CheckCircle className="w-4 h-4" />
                                    </>
                                )}
                            </button>

                            <div className="text-center pt-4 border-t border-slate-100">
                                {cooldown > 0 ? (
                                    <p className="text-[10px] font-black text-slate-400 uppercase tracking-wider">
                                        Resend Code available in <span className="text-[#185FA5] font-extrabold">{cooldown}s</span>
                                    </p>
                                ) : (
                                    <button
                                        type="button"
                                        onClick={handleResend}
                                        disabled={resending}
                                        className="inline-flex items-center space-x-1.5 text-xs font-black text-[#185FA5] hover:text-[#144f8a] uppercase tracking-wider cursor-pointer"
                                    >
                                        {resending ? (
                                            <>
                                                <Loader2 className="w-3.5 h-3.5 animate-spin" />
                                                <span>Requesting...</span>
                                            </>
                                        ) : (
                                            <>
                                                <RefreshCw className="w-3.5 h-3.5" />
                                                <span>Resend Passcode</span>
                                            </>
                                        )}
                                    </button>
                                )}
                            </div>

                        </form>

                    </div>

                    <div className="mt-8 text-center select-none">
                        <Link href="/employer/register" className="inline-flex items-center space-x-2 text-xs font-bold text-slate-400 hover:text-slate-600 uppercase tracking-widest">
                            <ArrowLeft className="w-4 h-4" />
                            <span>Change Email / Back</span>
                        </Link>
                    </div>
                </div>
            </div>
        </div>
    );
}
