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

export default function CreatePassword() {
    const [data, setData] = useState({
        password: '',
        password_confirmation: '',
    });

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

    // Live password strength validation
    const [strength, setStrength] = useState({
        length: false,
        upper: false,
        lower: false,
        number: false,
        special: false
    });

    useEffect(() => {
        const pass = data.password;
        setStrength({
            length: pass.length >= 8,
            upper: /[A-Z]/.test(pass),
            lower: /[a-z]/.test(pass),
            number: /[0-9]/.test(pass),
            special: /[^A-Za-z0-9]/.test(pass)
        });
    }, [data.password]);

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

    const isAllCriteriaMet = Object.values(strength).every(Boolean);

    const validateForm = () => {
        const newErrors = {};
        
        if (!data.password) {
            newErrors.password = 'Password is required.';
        } else if (!isAllCriteriaMet) {
            newErrors.password = 'Password must meet all complexity requirements.';
        }

        if (!data.password_confirmation) {
            newErrors.password_confirmation = 'Confirm password is required.';
        } else if (data.password !== data.password_confirmation) {
            newErrors.password_confirmation = 'Passwords do not match.';
        }

        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/create-password', data);
            toast.success('Registration finalized! Welcome to Migrant.');
            router.visit('/employer/dashboard');
        } catch (err) {
            if (err.response) {
                if (err.response.status === 422) {
                    setErrors(err.response.data.errors || {});
                    toast.error('Validation failed. Please verify password requirements.');
                } else {
                    toast.error('Failed to complete enrollment. Please try again.');
                }
            } else {
                toast.error('Network error. Please check your 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 === 4 
                                ? 'bg-[#185FA5] text-white border-[#185FA5] shadow-xs' 
                                : 'bg-blue-50 text-[#185FA5] border-blue-200'
                        }`}>
                            {s.step}
                        </div>
                        <span className={`text-[10px] font-bold tracking-tight ${
                            s.step === 4 ? '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>
    );

    const rules = [
        { key: 'length', text: 'At least 8 characters' },
        { key: 'upper', text: 'One uppercase letter (A-Z)' },
        { key: 'lower', text: 'One lowercase letter (a-z)' },
        { key: 'number', text: 'One numerical digit (0-9)' },
        { key: 'special', text: 'One special symbol (e.g. @, #, $, %)' }
    ];

    return (
        <div className="min-h-screen grid grid-cols-1 lg:grid-cols-12 bg-slate-50 font-sans">
            <Head title="Secure Password Setup - 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 Set Password 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">Set Password</h2>
                        <p className="text-xs text-gray-500 mt-1">Configure your portal access password</p>
                    </div>

                    <form onSubmit={handleSubmit} noValidate className="space-y-4">
                        {/* Password input */}
                        <div className="space-y-2">
                            <label className="block text-xs font-medium text-gray-700">Secure Password</label>
                            <div className="relative group">
                                <Lock className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 group-focus-within:text-[#185FA5] transition-colors" />
                                <input
                                    type={showPassword ? 'text' : 'password'}
                                    value={data.password}
                                    onChange={(e) => handleInputChange('password', e.target.value)}
                                    placeholder="••••••••"
                                    className={`w-full pl-10 pr-10 py-2.5 bg-slate-50 border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-[#185FA5]/20 focus:border-[#185FA5] focus:bg-white transition-all ${
                                        errors.password ? 'border-red-500 focus:ring-red-500/20' : 'border-slate-300'
                                    }`}
                                />
                                <button
                                    type="button"
                                    onClick={() => setShowPassword(!showPassword)}
                                    className="absolute right-3.5 top-1/2 -translate-y-1/2 p-1 text-gray-400 hover:text-gray-600"
                                >
                                    {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                                </button>
                            </div>
                            {errors.password && (
                                <p className="text-xs text-red-500 mt-1">
                                    {Array.isArray(errors.password) ? errors.password[0] : errors.password}
                                </p>
                            )}
                        </div>

                        {/* Confirm Password input */}
                        <div className="space-y-2">
                            <label className="block text-xs font-medium text-gray-700">Confirm Password</label>
                            <div className="relative group">
                                <Lock className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 group-focus-within:text-[#185FA5] transition-colors" />
                                <input
                                    type={showPassword ? 'text' : 'password'}
                                    value={data.password_confirmation}
                                    onChange={(e) => handleInputChange('password_confirmation', e.target.value)}
                                    placeholder="••••••••"
                                    className={`w-full pl-10 pr-4 py-2.5 bg-slate-50 border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-[#185FA5]/20 focus:border-[#185FA5] focus:bg-white transition-all ${
                                        errors.password_confirmation ? 'border-red-500 focus:ring-red-500/20' : 'border-slate-300'
                                    }`}
                                />
                            </div>
                            {errors.password_confirmation && (
                                <p className="text-xs text-red-500 mt-1">
                                    {Array.isArray(errors.password_confirmation) ? errors.password_confirmation[0] : errors.password_confirmation}
                                </p>
                            )}
                        </div>

                        {/* Password Rules Checklist */}
                        <div className="bg-slate-50 p-4 rounded-xl border border-slate-100 space-y-2">
                            <h4 className="text-[10px] font-bold text-gray-500 uppercase tracking-widest">Complexity Checklist</h4>
                            <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-1.5">
                                {rules.map((rule) => {
                                    const isMet = strength[rule.key];
                                    return (
                                        <div key={rule.key} className="flex items-center space-x-2">
                                            <div className={`w-3.5 h-3.5 rounded-full flex items-center justify-center border transition-all ${
                                                isMet 
                                                    ? 'bg-emerald-500 border-emerald-600 text-white' 
                                                    : 'bg-white border-slate-200 text-slate-300'
                                            }`}>
                                                {isMet ? <Check className="w-2 h-2" /> : null}
                                            </div>
                                            <span className={`text-[10px] ${
                                                isMet ? 'text-gray-700 font-medium' : 'text-gray-400'
                                            }`}>{rule.text}</span>
                                        </div>
                                    );
                                })}
                            </div>
                        </div>

                        <button
                            type="submit"
                            disabled={loading || !isAllCriteriaMet || data.password !== data.password_confirmation}
                            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-50 disabled:cursor-not-allowed mt-4"
                        >
                            {loading ? (
                                <Loader2 className="w-5 h-5 animate-spin mr-2" />
                            ) : (
                                'Submit & Activate Account'
                            )}
                        </button>
                    </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">
                            <X className="w-3.5 h-3.5 mr-1" />
                            <span>Cancel Registration</span>
                        </Link>
                    </div>
                </div>
            </div>
        </div>
    );
}
