import React, { useState, useEffect } from 'react';
import { Head, Link, router } from '@inertiajs/react';
import axios from 'axios';
import { toast } from 'sonner';
import { 
    ArrowLeft, 
    MailCheck,
    Loader2,
    RefreshCw,
    KeyRound,
    Users,
    DollarSign,
    MessageSquare
} 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 {
            await axios.post('/employer/verify-email', { otp });
            toast.success('Email verified successfully! Let\'s choose a subscription plan.');
            router.visit('/employer/register-payment');
        } 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 {
            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="w-full flex items-center justify-center space-x-1 sm:space-x-2 select-none pb-4 border-b border-slate-100">
            {[
                { step: 1, label: 'Register' },
                { step: 2, label: 'Verify' },
                { step: 3, label: 'Payment' },
                { step: 4, label: 'Password' }
            ].map((s) => (
                <React.Fragment key={s.step}>
                    <div className="flex items-center space-x-1 sm:space-x-1.5">
                        <div className={`w-5 h-5 rounded-full flex items-center justify-center font-bold text-[10px] border transition-all duration-300 ${
                            s.step === 2 
                                ? 'bg-[#185FA5] text-white border-[#185FA5] shadow-xs' 
                                : s.step < 2
                                    ? 'bg-blue-50 text-[#185FA5] border-blue-200'
                                    : 'bg-white text-slate-400 border-slate-200'
                        }`}>
                            {s.step}
                        </div>
                        <span className={`text-[10px] font-bold tracking-tight ${
                            s.step === 2 ? 'text-[#185FA5]' : 'text-slate-400'
                        }`}>
                            {s.label}
                        </span>
                    </div>
                    {s.step < 4 && (
                        <div className="w-4 sm:w-6 h-0.5 bg-slate-100" />
                    )}
                </React.Fragment>
            ))}
        </div>
    );

    return (
        <div className="min-h-screen grid grid-cols-1 lg:grid-cols-12 bg-slate-50 font-sans">
            <Head title="Verify Email - Migrant Portal" />

            {/* Left Brand Panel (Desktop Only) */}
            <div className="hidden lg:flex lg:col-span-5 bg-[#185FA5] p-12 flex-col justify-between text-white relative overflow-hidden select-none">
                <div className="absolute inset-0 bg-gradient-to-br from-blue-600/20 to-black/30 pointer-events-none" />
                
                <div className="relative z-10 space-y-6">
                    <div className="flex items-center space-x-3">
                        <div className="w-10 h-10 bg-white text-[#185FA5] rounded-xl flex items-center justify-center font-bold text-xl shadow-md">
                            M
                        </div>
                        <span className="font-bold text-2xl tracking-tight">Migrant Portal</span>
                    </div>

                    <div className="space-y-3 pt-6">
                        <span className="inline-block px-3 py-1 bg-white/10 border border-white/20 rounded-full text-xs font-semibold uppercase tracking-wider">
                            Employer Registration
                        </span>
                        <h1 className="text-4xl font-extrabold tracking-tight leading-tight">
                            Find verified domestic workers directly.
                        </h1>
                        <p className="text-blue-100 text-sm font-medium">
                            Unlock direct access to top domestic candidates with a Migrant premium subscription. Find, interview, and hire directly without middlemen.
                        </p>
                    </div>

                    {/* Stat Row */}
                    <div className="grid grid-cols-3 gap-4 pt-8 border-t border-white/10">
                        <div className="bg-white/10 backdrop-blur-sm p-4 rounded-xl border border-white/10 text-center space-y-1">
                            <Users className="w-6 h-6 text-emerald-300 mx-auto" />
                            <div className="font-bold text-lg">500+</div>
                            <div className="text-[10px] text-blue-100 uppercase tracking-wider font-semibold">Verified Workers</div>
                        </div>

                        <div className="bg-white/10 backdrop-blur-sm p-4 rounded-xl border border-white/10 text-center space-y-1">
                            <DollarSign className="w-6 h-6 text-emerald-300 mx-auto" />
                            <div className="font-bold text-lg">Premium</div>
                            <div className="text-[10px] text-blue-100 uppercase tracking-wider font-semibold">Employer Access</div>
                        </div>

                        <div className="bg-white/10 backdrop-blur-sm p-4 rounded-xl border border-white/10 text-center space-y-1">
                            <MessageSquare className="w-6 h-6 text-emerald-300 mx-auto" />
                            <div className="font-bold text-lg">Direct</div>
                            <div className="text-[10px] text-blue-100 uppercase tracking-wider font-semibold">Messaging</div>
                        </div>
                    </div>
                </div>

                <div className="relative z-10 text-xs text-blue-200 font-medium">
                    © 2026 Migrant. All rights reserved.
                </div>
            </div>

            {/* Right Verify Form */}
            <div className="col-span-1 lg:col-span-7 flex flex-col justify-center items-center p-6 sm:p-12 overflow-y-auto">
                <div className="w-full max-w-lg bg-white rounded-2xl shadow-sm border border-slate-200 p-8 space-y-6">
                    {renderStepIndicator()}
                    
                    <div>
                        <h2 className="text-2xl font-bold text-gray-900 tracking-tight">Verify Email</h2>
                        <p className="text-xs text-gray-500 mt-1">Verify your employer registration</p>
                    </div>

                    <div className="bg-white p-2 text-center">
                        <div className="w-12 h-12 bg-blue-50 text-[#185FA5] rounded-xl flex items-center justify-center mx-auto mb-3 border border-blue-100 shadow-sm">
                            <MailCheck className="w-6 h-6" />
                        </div>
                        <h3 className="text-sm font-bold text-gray-900">Check Your Email</h3>
                        <p className="text-xs text-gray-500 mt-1">
                            We sent a 6-digit verification code to:
                            <span className="text-[#185FA5] font-semibold block mt-0.5">{email}</span>
                        </p>
                    </div>

                    <form onSubmit={handleSubmit} noValidate className="space-y-6">
                        <div className="space-y-2">
                            <label className="block text-xs font-medium text-gray-700 text-center">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-gray-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-3 bg-slate-50 border rounded-xl text-center text-xl font-bold tracking-[0.25em] focus:outline-none focus:ring-2 focus:ring-[#185FA5]/20 focus:border-[#185FA5] focus:bg-white transition-all outline-none ${
                                        errors.otp ? 'border-red-500 focus:ring-red-500/20' : 'border-slate-300'
                                    }`}
                                />
                            </div>
                            {errors.otp && (
                                <p className="text-xs text-red-500 text-center mt-1">
                                    {Array.isArray(errors.otp) ? errors.otp[0] : errors.otp}
                                </p>
                            )}
                        </div>

                        <button
                            type="submit"
                            disabled={loading || otp.length !== 6}
                            className="w-full bg-[#185FA5] hover:bg-[#0C447C] active:bg-[#08305c] text-white rounded-xl h-11 font-semibold text-sm transition-colors shadow-sm flex items-center justify-center disabled:opacity-70 disabled:cursor-not-allowed mt-4"
                        >
                            {loading ? (
                                <Loader2 className="w-5 h-5 animate-spin mr-2" />
                            ) : (
                                'Confirm Verification'
                            )}
                        </button>

                        <div className="text-center pt-4 border-t border-slate-100">
                            {cooldown > 0 ? (
                                <p className="text-xs text-gray-500">
                                    Resend code in <span className="text-[#185FA5] font-semibold">{cooldown}s</span>
                                </p>
                            ) : (
                                <button
                                    type="button"
                                    onClick={handleResend}
                                    disabled={resending}
                                    className="inline-flex items-center space-x-1 text-xs font-bold text-[#185FA5] hover:underline cursor-pointer"
                                >
                                    {resending ? (
                                        <>
                                            <Loader2 className="w-3.5 h-3.5 animate-spin mr-1" />
                                            <span>Requesting...</span>
                                        </>
                                    ) : (
                                        <>
                                            <RefreshCw className="w-3 h-3 mr-1" />
                                            <span>Resend Passcode</span>
                                        </>
                                    )}
                                </button>
                            )}
                        </div>
                    </form>

                    <div className="border-t border-slate-100 pt-6 text-center">
                        <Link href="/employer/register" className="inline-flex items-center space-x-1 text-xs text-gray-600 font-medium hover:text-[#185FA5] hover:underline">
                            <ArrowLeft className="w-3.5 h-3.5 mr-1" />
                            <span>Change Email / Back</span>
                        </Link>
                    </div>
                </div>
            </div>
        </div>
    );
}
