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

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

    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]{7,15}$/.test(data.phone)) {
            newErrors.phone = 'Please enter a valid mobile number (7-15 digits without country code).';
        }
        
        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);

        try {
            await axios.post('/employer/register', 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: '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 === 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>
                        <span className={`text-[10px] font-bold tracking-tight ${
                            s.step === 1 ? '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="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>
                            <input
                                type="tel"
                                value={data.phone}
                                onChange={(e) => handleInputChange('phone', e.target.value)}
                                placeholder="e.g. 501234567"
                                className={`w-full px-3.5 py-3 rounded-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]'
                                }`}
                            />
                            {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>

                        <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>
    );
}
