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

export default function RegisterPayment({ email, plans }) {
    const [selectedPlan, setSelectedPlan] = useState(null);
    const [showPayTabsModal, setShowPayTabsModal] = useState(false);
    const [loading, setLoading] = useState(false);

    // Card inputs for PayTabs Gateway
    const [cardName, setCardName] = useState('');
    const [cardNumber, setCardNumber] = useState('');
    const [cardExpiry, setCardExpiry] = useState('');
    const [cardCvv, setCardCvv] = useState('');

    const handleSelectPlan = (plan) => {
        setSelectedPlan(plan);
        setShowPayTabsModal(true);
    };

    const handlePayTabsSubmit = async (e) => {
        e.preventDefault();
        
        if (cardNumber.length < 16) {
            toast.error("💳 Invalid card number format");
            return;
        }

        setLoading(true);
        setShowPayTabsModal(false);

        try {
            const simulatedTxnId = 'TXN-' + Math.random().toString(36).substr(2, 9).toUpperCase();
            
            await axios.post('/employer/register-payment', {
                plan_id: selectedPlan.id,
                amount_aed: parseFloat(selectedPlan.price),
                paytabs_transaction_id: simulatedTxnId
            });

            toast.success(`🎉 Payment Approved by PayTabs!`, {
                description: `Successfully registered for ${selectedPlan.name}. Now let's finalize your password setup.`,
                duration: 5000,
            });

            router.visit('/employer/create-password');
        } catch (err) {
            toast.error("Payment 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: '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 === 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>
                        <span className={`text-[10px] font-bold tracking-tight ${
                            s.step === 3 ? '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="Purchase Annual Subscription - Migrant Portal" />

            {/* Left Brand Panel */}
            <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">
                            Step 3: Annual Pass
                        </span>
                        <h1 className="text-4xl font-extrabold tracking-tight leading-tight">
                            Purchase annual subscription to access.
                        </h1>
                        <p className="text-blue-100 text-sm font-medium">
                            Unlock candidate contact details, direct messages, and complete MOHRE TADBEER compliant digital dossiers.
                        </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">Sponsor 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 Payment View */}
            <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-2xl bg-white rounded-3xl shadow-sm border border-slate-200 p-8 space-y-6">
                    {renderStepIndicator()}
                    
                    <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 pb-4">
                        <div>
                            <h2 className="text-2xl font-bold text-gray-900 tracking-tight">Sponsor Subscription</h2>
                            <p className="text-xs text-gray-500 mt-1">Select and purchase a premium pass</p>
                        </div>
                    </div>

                    <div className="grid grid-cols-1 md:grid-cols-3 gap-4 pt-2">
                        {plans.map((plan) => (
                            <div
                                key={plan.id}
                                className="bg-white rounded-2xl border border-slate-200 hover:border-slate-300 shadow-sm flex flex-col justify-between overflow-hidden relative p-5 space-y-4"
                            >
                                <div>
                                    <h3 className="font-bold text-sm text-slate-800">{plan.name}</h3>
                                    <div className="mt-2 flex items-baseline space-x-1">
                                        <span className="text-xl font-black text-slate-900 tracking-tight">{plan.price}</span>
                                        <span className="text-[10px] font-semibold text-slate-400">/ month</span>
                                    </div>
                                    
                                    <ul className="space-y-2 pt-4 border-t border-slate-100 mt-4">
                                        {plan.features.slice(0, 3).map(f => (
                                            <li key={f} className="flex items-start space-x-2 text-[10px] text-slate-600 font-semibold">
                                                <Check className="w-3.5 h-3.5 text-emerald-600 flex-shrink-0" />
                                                <span>{f}</span>
                                            </li>
                                        ))}
                                    </ul>
                                </div>

                                <button
                                    type="button"
                                    onClick={() => handleSelectPlan(plan)}
                                    className="w-full h-9 rounded-lg bg-[#185FA5] hover:bg-[#144f8a] text-white font-bold text-[10px] flex items-center justify-center transition-all shadow-xs mt-4"
                                >
                                    Select Plan Tier
                                </button>
                            </div>
                        ))}
                    </div>
                </div>
            </div>

            {/* Interactive PayTabs Checkout Modal Overlay */}
            {showPayTabsModal && selectedPlan && (
                <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-4 z-50">
                    <div className="bg-white rounded-3xl w-full max-w-md border border-slate-200 shadow-2xl p-6 relative animate-zoom-in space-y-6">
                        <button
                            onClick={() => setShowPayTabsModal(false)}
                            className="absolute top-4 right-4 p-2 bg-slate-50 hover:bg-slate-100 rounded-full text-slate-400 hover:text-slate-600 transition-colors"
                        >
                            <X className="w-5 h-5" />
                        </button>

                        {/* PayTabs Header */}
                        <div className="flex items-center justify-between border-b border-slate-100 pb-3">
                            <div className="flex items-center space-x-2">
                                <CreditCard className="w-6 h-6 text-red-600" />
                                <span className="font-extrabold text-sm text-slate-900 tracking-tight uppercase">PayTabs Secured Checkout</span>
                            </div>
                            <span className="text-[8px] bg-red-50 text-red-700 px-2 py-0.5 rounded font-black tracking-widest uppercase">
                                Gateway v4.0
                            </span>
                        </div>

                        {/* Order Summary */}
                        <div className="bg-slate-50 p-4 rounded-2xl border border-slate-200/60 flex justify-between items-center text-xs font-bold text-slate-700">
                            <div>
                                <span className="text-[10px] text-slate-400 uppercase tracking-widest">Order description</span>
                                <div className="text-slate-900">{selectedPlan.name} Subscription</div>
                            </div>
                            <div className="text-right">
                                <span className="text-[10px] text-slate-400 uppercase tracking-widest">Total amount</span>
                                <div className="text-emerald-700 text-sm font-black">{selectedPlan.price}</div>
                            </div>
                        </div>

                        {/* PayTabs CC Form */}
                        <form onSubmit={handlePayTabsSubmit} className="space-y-4">
                            <div className="space-y-3.5 text-xs">
                                <div>
                                    <label className="block font-bold text-slate-700 mb-1">Cardholder Name</label>
                                    <input 
                                        type="text"
                                        placeholder="e.g. Fatima Al Mansoori"
                                        value={cardName}
                                        onChange={(e) => setCardName(e.target.value)}
                                        className="w-full p-2.5 border border-slate-300 rounded-xl"
                                        required
                                    />
                                </div>

                                <div>
                                    <label className="block font-bold text-slate-700 mb-1">Card Number</label>
                                    <input 
                                        type="text"
                                        maxLength="16"
                                        placeholder="1234 5678 9101 1121"
                                        value={cardNumber}
                                        onChange={(e) => setCardNumber(e.target.value.replace(/\D/g, ''))}
                                        className="w-full p-2.5 border border-slate-300 rounded-xl font-mono text-sm"
                                        required
                                    />
                                </div>

                                <div className="grid grid-cols-2 gap-4">
                                    <div>
                                        <label className="block font-bold text-slate-700 mb-1">Expiry Date (MM/YY)</label>
                                        <input 
                                            type="text"
                                            placeholder="12/28"
                                            value={cardExpiry}
                                            onChange={(e) => setCardExpiry(e.target.value)}
                                            className="w-full p-2.5 border border-slate-300 rounded-xl"
                                            required
                                        />
                                    </div>
                                    <div>
                                        <label className="block font-bold text-slate-700 mb-1">Security Code (CVV)</label>
                                        <input 
                                            type="password"
                                            maxLength="3"
                                            placeholder="***"
                                            value={cardCvv}
                                            onChange={(e) => setCardCvv(e.target.value.replace(/\D/g, ''))}
                                            className="w-full p-2.5 border border-slate-300 rounded-xl font-mono text-sm"
                                            required
                                        />
                                    </div>
                                </div>
                            </div>

                            <div className="pt-4 border-t border-slate-100 flex items-center justify-between text-[10px] text-slate-500">
                                <span className="flex items-center space-x-1 font-bold">
                                    <Lock className="w-3.5 h-3.5 text-emerald-600" />
                                    <span>256-bit PCI DSS Cryptography Protected</span>
                                </span>
                            </div>

                            <button
                                type="submit"
                                className="w-full bg-red-600 hover:bg-red-700 text-white py-3.5 rounded-2xl font-black text-xs uppercase tracking-widest shadow-lg shadow-red-500/10 flex items-center justify-center space-x-2"
                            >
                                <span>Authorize Payment</span>
                                <ArrowRight className="w-4 h-4" />
                            </button>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
}
