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

export default function UploadEmiratesId({ email }) {
    const [file, setFile] = useState(null);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);

    const handleFileChange = (e) => {
        const selectedFile = e.target.files[0];
        if (selectedFile) {
            if (selectedFile.size > 10240 * 1024) {
                setError('The document must not exceed 10MB.');
                toast.error('The document must not exceed 10MB.');
                return;
            }
            setFile(selectedFile);
            setError(null);
        }
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        if (!file) {
            setError('Please upload a clear scan or image of your Emirates ID.');
            toast.error('Please upload your Emirates ID document.');
            return;
        }

        setLoading(true);
        setError(null);

        const formData = new FormData();
        formData.append('emirates_id_file', file);

        try {
            await axios.post('/employer/upload-emirates-id', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            });
            toast.success('Emirates ID scanned successfully. Data extracted and document deleted.');
            router.visit('/employer/register-payment');
        } catch (err) {
            if (err.response && err.response.data && err.response.data.errors) {
                setError(err.response.data.errors.emirates_id_file || 'Validation failed.');
                toast.error('Validation failed. Please verify the document.');
            } else {
                toast.error('Scan extraction failed. Please try again.');
            }
        } 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 === 3 
                                ? 'bg-[#185FA5] text-white border-[#185FA5] shadow-xs' 
                                : s.step < 3
                                    ? 'bg-blue-50 text-[#185FA5] border-blue-200'
                                    : 'bg-white text-slate-400 border-slate-200'
                        }`}>
                            {s.step}
                        </div>
                        {s.step === 3 && (
                            <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="Upload Emirates ID - 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 Form Container */}
            <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">Emirates ID Verification</h2>
                        <p className="text-xs text-gray-500 mt-1">Upload your identity document for quick OCR scanning</p>
                    </div>

                    {/* Security & Disclaimer Banner */}
                    <div className="bg-blue-50/70 border border-blue-100 rounded-xl p-4 flex items-start space-x-3">
                        <ShieldCheck className="w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5" />
                        <div className="space-y-1">
                            <h4 className="text-xs font-bold text-blue-900 uppercase tracking-wider">Data Privacy Disclaimer</h4>
                            <p className="text-[11px] text-blue-700 leading-relaxed font-medium">
                                We do not store your physical Emirates ID document. Your card is temporarily scanned only to securely extract the ID number and expiry date via automated OCR, and the file is permanently deleted immediately after extraction.
                            </p>
                        </div>
                    </div>

                    <form onSubmit={handleSubmit} className="space-y-6">
                        {/* File Upload Area */}
                        <div>
                            <label className="block text-xs font-semibold text-gray-700 mb-2 uppercase tracking-wider">
                                Emirates ID Document
                            </label>
                            
                            <div className={`border-2 border-dashed rounded-xl p-6 text-center transition-all relative ${
                                file 
                                    ? 'border-emerald-500 bg-emerald-50/20' 
                                    : 'border-slate-300 hover:border-[#185FA5] bg-slate-50/50'
                            }`}>
                                <input
                                    type="file"
                                    accept="image/jpeg,image/png,image/jpg,application/pdf"
                                    onChange={handleFileChange}
                                    className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
                                />

                                {!file ? (
                                    <div className="space-y-2">
                                        <UploadCloud className="w-8 h-8 text-slate-400 mx-auto" />
                                        <p className="text-xs font-bold text-gray-700">
                                            Click or Drag image/PDF file here
                                        </p>
                                        <p className="text-[10px] text-gray-400">
                                            Supported: JPG, JPEG, PNG, PDF (Max 10MB)
                                        </p>
                                    </div>
                                ) : (
                                    <div className="flex items-center justify-center space-x-3">
                                        <FileText className="w-8 h-8 text-emerald-600" />
                                        <div className="text-left">
                                            <p className="text-xs font-bold text-gray-800 truncate max-w-[200px]">
                                                {file.name}
                                            </p>
                                            <p className="text-[10px] text-gray-400">
                                                {(file.size / (1024 * 1024)).toFixed(2)} MB • Ready for Scan
                                            </p>
                                        </div>
                                    </div>
                                )}
                            </div>
                            
                            {error && (
                                <p className="mt-2 text-xs text-red-500 font-semibold flex items-center">
                                    <ShieldAlert className="w-3.5 h-3.5 mr-1" />
                                    {error}
                                </p>
                            )}
                        </div>

                        <button
                            type="submit"
                            disabled={loading || !file}
                            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"
                        >
                            {loading ? (
                                <Loader2 className="w-5 h-5 animate-spin mr-2" />
                            ) : (
                                'Scan & Extract Data'
                            )}
                        </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">
                            <ArrowLeft className="w-3.5 h-3.5 mr-1" />
                            <span>Change Email / Back</span>
                        </Link>
                    </div>
                </div>
            </div>
        </div>
    );
}
