import React, { useState, useRef, useEffect } from 'react';
import { Head, Link, router } from '@inertiajs/react';
import axios from 'axios';
import { toast } from 'sonner';
import { 
    Loader2,
    Users,
    DollarSign,
    MessageSquare,
    ChevronDown,
    Search
} from 'lucide-react';

// Common country dial codes with flag emojis
const COUNTRY_CODES = [
    { code: 'AE', dial: '+971', flag: '🇦🇪', name: 'United Arab Emirates' },
    { code: 'SA', dial: '+966', flag: '🇸🇦', name: 'Saudi Arabia' },
    { code: 'IN', dial: '+91',  flag: '🇮🇳', name: 'India' },
    { code: 'PK', dial: '+92',  flag: '🇵🇰', name: 'Pakistan' },
    { code: 'PH', dial: '+63',  flag: '🇵🇭', name: 'Philippines' },
    { code: 'BD', dial: '+880', flag: '🇧🇩', name: 'Bangladesh' },
    { code: 'LK', dial: '+94',  flag: '🇱🇰', name: 'Sri Lanka' },
    { code: 'NP', dial: '+977', flag: '🇳🇵', name: 'Nepal' },
    { code: 'EG', dial: '+20',  flag: '🇪🇬', name: 'Egypt' },
    { code: 'JO', dial: '+962', flag: '🇯🇴', name: 'Jordan' },
    { code: 'LB', dial: '+961', flag: '🇱🇧', name: 'Lebanon' },
    { code: 'IQ', dial: '+964', flag: '🇮🇶', name: 'Iraq' },
    { code: 'KW', dial: '+965', flag: '🇰🇼', name: 'Kuwait' },
    { code: 'QA', dial: '+974', flag: '🇶🇦', name: 'Qatar' },
    { code: 'BH', dial: '+973', flag: '🇧🇭', name: 'Bahrain' },
    { code: 'OM', dial: '+968', flag: '🇴🇲', name: 'Oman' },
    { code: 'ET', dial: '+251', flag: '🇪🇹', name: 'Ethiopia' },
    { code: 'KE', dial: '+254', flag: '🇰🇪', name: 'Kenya' },
    { code: 'UG', dial: '+256', flag: '🇺🇬', name: 'Uganda' },
    { code: 'GH', dial: '+233', flag: '🇬🇭', name: 'Ghana' },
    { code: 'NG', dial: '+234', flag: '🇳🇬', name: 'Nigeria' },
    { code: 'ID', dial: '+62',  flag: '🇮🇩', name: 'Indonesia' },
    { code: 'MY', dial: '+60',  flag: '🇲🇾', name: 'Malaysia' },
    { code: 'GB', dial: '+44',  flag: '🇬🇧', name: 'United Kingdom' },
    { code: 'US', dial: '+1',   flag: '🇺🇸', name: 'United States' },
];

function CountryCodeSelector({ value, onChange, hasError }) {
    const [open, setOpen] = useState(false);
    const [search, setSearch] = useState('');
    const ref = useRef(null);
    const searchRef = useRef(null);

    const selected = COUNTRY_CODES.find(c => c.dial === value) || COUNTRY_CODES[0];

    const filtered = COUNTRY_CODES.filter(c =>
        c.name.toLowerCase().includes(search.toLowerCase()) ||
        c.dial.includes(search)
    );

    useEffect(() => {
        const handler = (e) => {
            if (ref.current && !ref.current.contains(e.target)) setOpen(false);
        };
        document.addEventListener('mousedown', handler);
        return () => document.removeEventListener('mousedown', handler);
    }, []);

    useEffect(() => {
        if (open && searchRef.current) searchRef.current.focus();
    }, [open]);

    return (
        <div ref={ref} className="relative">
            <button
                type="button"
                onClick={() => { setOpen(o => !o); setSearch(''); }}
                className={`flex items-center gap-1.5 px-3 py-3 h-full rounded-l-xl border-r-0 border text-sm font-medium whitespace-nowrap transition-all focus:outline-none focus:ring-2 ${
                    hasError
                        ? 'border-red-500 focus:ring-red-500/20 bg-red-50'
                        : 'border-slate-300 focus:ring-[#185FA5]/20 bg-slate-50 hover:bg-slate-100'
                }`}
            >
                <span className="text-base leading-none">{selected.flag}</span>
                <span className="text-slate-700 text-xs">{selected.dial}</span>
                <ChevronDown className={`w-3 h-3 text-slate-500 transition-transform ${open ? 'rotate-180' : ''}`} />
            </button>

            {open && (
                <div className="absolute left-0 top-full mt-1 z-50 w-72 bg-white border border-slate-200 rounded-xl shadow-xl overflow-hidden">
                    {/* Search */}
                    <div className="p-2 border-b border-slate-100">
                        <div className="flex items-center gap-2 px-2.5 py-1.5 bg-slate-50 rounded-lg border border-slate-200">
                            <Search className="w-3.5 h-3.5 text-slate-400 shrink-0" />
                            <input
                                ref={searchRef}
                                type="text"
                                value={search}
                                onChange={e => setSearch(e.target.value)}
                                placeholder="Search country..."
                                className="flex-1 bg-transparent text-xs outline-none text-slate-700 placeholder-slate-400"
                            />
                        </div>
                    </div>

                    {/* List */}
                    <ul className="max-h-52 overflow-y-auto">
                        {filtered.length === 0 ? (
                            <li className="px-4 py-3 text-xs text-slate-400 text-center">No results found</li>
                        ) : filtered.map(c => (
                            <li key={c.code}>
                                <button
                                    type="button"
                                    onClick={() => { onChange(c.dial); setOpen(false); }}
                                    className={`w-full flex items-center gap-3 px-4 py-2.5 text-sm hover:bg-slate-50 transition-colors ${
                                        c.dial === value ? 'bg-blue-50 text-[#185FA5] font-semibold' : 'text-slate-700'
                                    }`}
                                >
                                    <span className="text-base">{c.flag}</span>
                                    <span className="flex-1 text-left text-xs">{c.name}</span>
                                    <span className="text-xs text-slate-500 font-mono">{c.dial}</span>
                                </button>
                            </li>
                        ))}
                    </ul>
                </div>
            )}
        </div>
    );
}

export default function Register() {
    const [countryCode, setCountryCode] = useState('+971');
    const [data, setData] = useState({
        name: '',
        email: '',
        phone: '',
        address: '',
    });

    const [loading, setLoading] = useState(false);
    const [errors, setErrors] = useState({});

    const handleInputChange = (field, value) => {
        setData(prev => ({ ...prev, [field]: value }));
        if (errors[field]) {
            setErrors(prev => ({ ...prev, [field]: null }));
        }
    };

    const validateForm = () => {
        const newErrors = {};
        
        if (!data.name.trim()) {
            newErrors.name = 'Sponsor name is required.';
        }
        
        if (!data.email.trim()) {
            newErrors.email = 'Email address is required.';
        } else if (!/\S+@\S+\.\S+/.test(data.email)) {
            newErrors.email = 'Please enter a valid email address.';
        }
        
        if (!data.phone.trim()) {
            newErrors.phone = 'Mobile number is required.';
        } else if (!/^[0-9]{4,14}$/.test(data.phone.replace(/^0+/, ''))) {
            newErrors.phone = 'Please enter a valid mobile number (digits only, without country code).';
        }
        
        if (!data.address.trim()) {
            newErrors.address = 'Address is required.';
        }
        
        setErrors(newErrors);
        return Object.keys(newErrors).length === 0;
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        setErrors({});

        if (!validateForm()) {
            toast.error('Validation failed. Please correct the fields in red.');
            return;
        }

        setLoading(true);

        const formData = new FormData();
        formData.append('name', data.name);
        formData.append('email', data.email);
        formData.append('phone', countryCode + data.phone.replace(/^0+/, ''));
        formData.append('country_code', countryCode);
        formData.append('address', data.address);

        try {
            await axios.post('/employer/register', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            });
            toast.success('Registration details saved! Verification code sent to your email.');
            router.visit('/employer/verify-email');
        } catch (err) {
            if (err.response) {
                if (err.response.status === 409) {
                    const errMsg = err.response.data?.errors?.email || 'This email address is already registered.';
                    setErrors({ email: errMsg });
                    toast.error(errMsg);
                } else if (err.response.status === 422) {
                    setErrors(err.response.data.errors || {});
                    toast.error('Validation failed. Please correct the fields in red.');
                } else {
                    toast.error('Something went wrong. Please try again.');
                }
            } else {
                toast.error('Network error. Please check your internet connection.');
            }
        } finally {
            setLoading(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: 'Emirates ID' },
                { step: 4, label: 'Payment' },
                { step: 5, 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 === 1 
                                ? 'bg-[#185FA5] text-white border-[#185FA5] shadow-xs' 
                                : s.step < 1
                                    ? 'bg-blue-50 text-[#185FA5] border-blue-200'
                                    : 'bg-white text-slate-400 border-slate-200'
                        }`}>
                            {s.step}
                        </div>
                        {s.step === 1 && (
                            <span className="text-[10px] font-bold tracking-tight text-[#185FA5]">
                                {s.label}
                            </span>
                        )}
                    </div>
                    {s.step < 5 && (
                        <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="Employer Registration - 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 Registration 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">Create Account</h2>
                        <p className="text-xs text-gray-500 mt-1">Register your employer portal to start searching</p>
                    </div>

                    <form onSubmit={handleSubmit} noValidate className="space-y-4">
                        {/* Company Name */}
                        {/* Sponsor Name */}
                        <div>
                            <label className="block text-xs font-semibold text-gray-700 mb-1.5 uppercase tracking-wider">Sponsor Name</label>
                            <input
                                type="text"
                                value={data.name}
                                onChange={(e) => handleInputChange('name', e.target.value)}
                                placeholder="e.g. Abdullah Bin Ahmed"
                                className={`w-full px-3.5 py-3 rounded-xl border text-sm focus:outline-none focus:ring-2 transition-all ${
                                    errors.name 
                                        ? 'border-red-500 focus:ring-red-500/20 focus:border-red-500' 
                                        : 'border-slate-300 focus:ring-[#185FA5]/20 focus:border-[#185FA5]'
                                }`}
                            />
                            {errors.name && (
                                <p className="mt-1.5 text-xs text-red-500 font-medium">
                                    {Array.isArray(errors.name) ? errors.name[0] : errors.name}
                                </p>
                            )}
                        </div>

                        {/* Email */}
                        <div>
                            <label className="block text-xs font-semibold text-gray-700 mb-1.5 uppercase tracking-wider">Email</label>
                            <input
                                type="email"
                                value={data.email}
                                onChange={(e) => handleInputChange('email', e.target.value)}
                                placeholder="employer@domain.com"
                                className={`w-full px-3.5 py-3 rounded-xl border text-sm focus:outline-none focus:ring-2 transition-all ${
                                    errors.email 
                                        ? 'border-red-500 focus:ring-red-500/20 focus:border-red-500' 
                                        : 'border-slate-300 focus:ring-[#185FA5]/20 focus:border-[#185FA5]'
                                }`}
                            />
                            {errors.email && (
                                <p className="mt-1.5 text-xs text-red-500 font-medium">
                                    {Array.isArray(errors.email) ? errors.email[0] : errors.email}
                                </p>
                            )}
                        </div>

                        {/* Mobile Number */}
                        <div>
                            <label className="block text-xs font-semibold text-gray-700 mb-1.5 uppercase tracking-wider">Mobile Number</label>
                            <div className="flex">
                                <CountryCodeSelector
                                    value={countryCode}
                                    onChange={setCountryCode}
                                    hasError={!!errors.phone}
                                />
                                <input
                                    type="tel"
                                    value={data.phone}
                                    onChange={(e) => handleInputChange('phone', e.target.value.replace(/[^0-9]/g, ''))}
                                    placeholder="501234567"
                                    className={`flex-1 px-3.5 py-3 rounded-r-xl border text-sm focus:outline-none focus:ring-2 transition-all ${
                                        errors.phone 
                                            ? 'border-red-500 focus:ring-red-500/20 focus:border-red-500' 
                                            : 'border-slate-300 focus:ring-[#185FA5]/20 focus:border-[#185FA5]'
                                    }`}
                                />
                            </div>
                            {errors.phone && (
                                <p className="mt-1.5 text-xs text-red-500 font-medium">
                                    {Array.isArray(errors.phone) ? errors.phone[0] : errors.phone}
                                </p>
                            )}
                        </div>

                        {/* Address */}
                        <div>
                            <label className="block text-xs font-semibold text-gray-700 mb-1.5 uppercase tracking-wider">Address</label>
                            <textarea
                                value={data.address}
                                onChange={(e) => handleInputChange('address', e.target.value)}
                                placeholder="e.g. Villa 14, Al Safa, Dubai, UAE"
                                rows="2"
                                className={`w-full px-3.5 py-3 rounded-xl border text-sm focus:outline-none focus:ring-2 transition-all ${
                                    errors.address 
                                        ? 'border-red-500 focus:ring-red-500/20 focus:border-red-500' 
                                        : 'border-slate-300 focus:ring-[#185FA5]/20 focus:border-[#185FA5]'
                                }`}
                            />
                            {errors.address && (
                                <p className="mt-1.5 text-xs text-red-500 font-medium">
                                    {Array.isArray(errors.address) ? errors.address[0] : errors.address}
                                </p>
                            )}
                        </div>


                        <button
                            type="submit"
                            disabled={loading}
                            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-2"
                        >
                            {loading ? (
                                <Loader2 className="w-5 h-5 animate-spin mr-2" />
                            ) : (
                                'Continue to Verification'
                            )}
                        </button>
                    </form>

                    <div className="border-t border-slate-100 pt-6 text-center">
                        <p className="text-xs text-gray-600 font-medium">
                            Already have an account?{' '}
                            <Link href="/employer/login" className="text-[#185FA5] font-bold hover:underline">
                                Sign in
                            </Link>
                        </p>
                    </div>
                </div>
            </div>
        </div>
    );
}
