import React, { useState, useEffect } from 'react';
import { Head, Link, router } from '@inertiajs/react';
import axios from 'axios';
import { toast } from 'sonner';
import { 
    ShieldCheck, 
    CheckCircle, 
    Eye, 
    EyeOff, 
    Lock,
    Loader2,
    Check,
    X
} 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 handleSubmit = async (e) => {
        e.preventDefault();
        
        if (!isAllCriteriaMet) {
            setErrors({ password: 'Password does not meet all security guidelines.' });
            toast.error('Password does not meet all security guidelines.');
            return;
        }

        if (data.password !== data.password_confirmation) {
            setErrors({ password_confirmation: 'Passwords do not match.' });
            toast.error('Passwords do not match.');
            return;
        }

        setLoading(true);
        setErrors({});

        try {
            const response = await axios.post('/employer/create-password', data);
            toast.success('Registration finalized! Welcome to the Marketplace.');
            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="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: '100%' }} />
            
            {[
                { 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 <= 3 
                            ? 'bg-[#185FA5] text-white border-blue-100 scale-110 shadow-lg' 
                            : 'bg-white text-slate-400 border-slate-50'
                    }`}>
                        {s.step === 3 && isAllCriteriaMet ? <Check className="w-5 h-5" /> : s.step}
                    </div>
                    <span className={`text-[9px] font-black uppercase mt-2 tracking-wider ${
                        s.step <= 3 ? 'text-[#185FA5]' : 'text-slate-400'
                    }`}>{s.label}</span>
                </div>
            ))}
        </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-[#F8FAFC] font-sans selection:bg-blue-100 selection:text-[#185FA5]">
            <Head title="Secure Password Setup - Step 3" />

            {/* 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">
                            Establish Secure Credentials.
                        </h1>
                        <p className="text-blue-100 text-lg font-medium leading-relaxed opacity-90">
                            Establish a robust password to ensure protection of your domestic hiring workspace.
                        </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">Security Configuration</h2>
                        <p className="text-sm font-bold text-slate-400 mt-2 uppercase tracking-widest">
                            Step 3 of 3: Configure Portal Access Key
                        </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">
                        
                        <form onSubmit={handleSubmit} className="space-y-6">
                            
                            {/* Password input */}
                            <div className="space-y-2">
                                <label className="text-[10px] font-black text-slate-500 uppercase tracking-widest ml-1">Secure Password</label>
                                <div className="relative group">
                                    <Lock 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={showPassword ? 'text' : 'password'}
                                        value={data.password}
                                        onChange={(e) => handleInputChange('password', e.target.value)}
                                        placeholder="••••••••"
                                        className={`w-full pl-12 pr-12 py-4 bg-slate-50 border rounded-2xl text-sm font-bold focus:ring-4 focus:ring-blue-100 focus:bg-white transition-all outline-none ${
                                            errors.password ? 'border-rose-400 bg-rose-50/20' : 'border-transparent'
                                        }`}
                                        required
                                    />
                                    <button
                                        type="button"
                                        onClick={() => setShowPassword(!showPassword)}
                                        className="absolute right-4 top-1/2 -translate-y-1/2 p-2 text-slate-400 hover:text-slate-600 cursor-pointer"
                                    >
                                        {showPassword ? <EyeOff className="w-4.5 h-4.5" /> : <Eye className="w-4.5 h-4.5" />}
                                    </button>
                                </div>
                                {errors.password && (
                                    <p className="text-xs text-rose-500 font-bold ml-1 uppercase tracking-wider">{errors.password[0] || errors.password}</p>
                                )}
                            </div>

                            {/* Confirm Password input */}
                            <div className="space-y-2">
                                <label className="text-[10px] font-black text-slate-500 uppercase tracking-widest ml-1">Confirm Access Key</label>
                                <div className="relative group">
                                    <Lock 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={showPassword ? 'text' : 'password'}
                                        value={data.password_confirmation}
                                        onChange={(e) => handleInputChange('password_confirmation', e.target.value)}
                                        placeholder="••••••••"
                                        className={`w-full pl-12 pr-4 py-4 bg-slate-50 border rounded-2xl text-sm font-bold focus:ring-4 focus:ring-blue-100 focus:bg-white transition-all outline-none ${
                                            errors.password_confirmation ? 'border-rose-400 bg-rose-50/20' : 'border-transparent'
                                        }`}
                                        required
                                    />
                                </div>
                                {errors.password_confirmation && (
                                    <p className="text-xs text-rose-500 font-bold ml-1 uppercase tracking-wider">{errors.password_confirmation[0] || errors.password_confirmation}</p>
                                )}
                            </div>

                            {/* Password Rules Checklist */}
                            <div className="bg-slate-50 p-6 rounded-3xl border border-slate-100 space-y-3">
                                <h4 className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Password Complexity Checklist</h4>
                                <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-2">
                                    {rules.map((rule) => {
                                        const isMet = strength[rule.key];
                                        return (
                                            <div key={rule.key} className="flex items-center space-x-2.5">
                                                <div className={`w-4 h-4 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.5 h-2.5" /> : null}
                                                </div>
                                                <span className={`text-[10px] font-bold ${
                                                    isMet ? 'text-slate-600' : 'text-slate-400'
                                                }`}>{rule.text}</span>
                                            </div>
                                        );
                                    })}
                                </div>
                            </div>

                            <button
                                type="submit"
                                disabled={loading || !isAllCriteriaMet || data.password !== data.password_confirmation}
                                className="w-full bg-emerald-600 hover:bg-emerald-700 disabled:opacity-50 disabled:hover:bg-emerald-600 text-white py-5 rounded-[24px] font-black text-xs uppercase tracking-[0.2em] transition-all shadow-xl shadow-emerald-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>Saving Employer Profile...</span>
                                    </>
                                ) : (
                                    <>
                                        <span>Submit & Activate Account</span>
                                        <ShieldCheck className="w-4 h-4" />
                                    </>
                                )}
                            </button>

                        </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">
                            <X className="w-4 h-4" />
                            <span>Cancel Registration</span>
                        </Link>
                    </div>
                </div>
            </div>
        </div>
    );
}
