import React, { useState } from 'react';
import { Head } from '@inertiajs/react';
import EmployerLayout from '../../Layouts/EmployerLayout';
import { useTranslation } from '../../lib/LanguageContext';
import { 
    CreditCard, 
    CheckCircle2, 
    AlertCircle, 
    ArrowRight, 
    Sparkles, 
    FileText, 
    Download, 
    ShieldCheck, 
    Clock, 
    User, 
    Building, 
    Check, 
    Lock, 
    RefreshCw, 
    X,
    TrendingUp
} from 'lucide-react';
import { toast } from 'sonner';

export default function Subscription({ currentPlan, expiresAt, plans }) {
    const { t } = useTranslation();
    const [selectedPlan, setSelectedPlan] = useState(null);
    const [showPayTabsModal, setShowPayTabsModal] = useState(false);
    const [showSuccess, setShowSuccess] = useState(false);
    
    // Card inputs for PayTabs Gateway
    const [cardName, setCardName] = useState('');
    const [cardNumber, setCardNumber] = useState('');
    const [cardExpiry, setCardExpiry] = useState('');
    const [cardCvv, setCardCvv] = useState('');
    const [billingEmail, setBillingEmail] = useState('sponsor@marketplace.ae');

    // Failed payment simulation
    const [simulatedFailedState, setSimulatedFailedState] = useState(false);
    const [activePlan, setActivePlan] = useState(currentPlan || 'Premium Employer Pass');

    // Payment History List
    const [invoices, setInvoices] = useState([
        { id: 'INV-2026-001', date: 'May 01, 2026', amount: '199 AED', status: 'Paid', plan: 'Premium Employer Pass' },
        { id: 'INV-2026-002', date: 'Apr 01, 2026', amount: '199 AED', status: 'Paid', plan: 'Premium Employer Pass' },
        { id: 'INV-2026-003', date: 'Mar 01, 2026', amount: '99 AED', status: 'Refunded', plan: 'Basic Search' }
    ]);

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

    const handlePayTabsSubmit = (e) => {
        e.preventDefault();
        
        if (cardNumber.length < 16) {
            toast.error(`💳 ${t('invalid_card_format', 'Invalid card number format')}`);
            return;
        }

        setShowPayTabsModal(false);
        setShowSuccess(true);
        setActivePlan(selectedPlan.name);
        
        // Add to invoices
        const newInvoice = {
            id: `INV-2026-0${invoices.length + 1}`,
            date: 'Today',
            amount: selectedPlan.price,
            status: 'Paid',
            plan: selectedPlan.name
        };
        setInvoices([newInvoice, ...invoices]);

        toast.success(`🎉 ${t('payment_approved', 'Payment Approved by PayTabs!')}`, {
            description: t('successfully_subscribed_desc', 'Successfully subscribed to {plan}. Premium access limits updated instantly.').replace('{plan}', selectedPlan.name),
            duration: 5000,
        });

        // Reset forms
        setCardName('');
        setCardNumber('');
        setCardExpiry('');
        setCardCvv('');

        setTimeout(() => setShowSuccess(false), 5000);
    };

    const triggerFailedPaymentSimulation = () => {
        setSimulatedFailedState(true);
        toast.warning(t('simulated_billing_failure_triggered', 'Simulated billing failure triggered!'), {
            description: t('simulated_billing_failure_desc', 'An automatic system warning will now request payment retry options.')
        });
    };

    const handleRetryPayment = () => {
        const premium = plans.find(p => p.id === 'premium') || plans[0];
        setSelectedPlan(premium);
        setShowPayTabsModal(true);
        setSimulatedFailedState(false);
    };

    const downloadReceipt = (invoiceId) => {
        toast.success(`📄 ${t('invoice_generated', 'Invoice {id} generated').replace('{id}', invoiceId)}`, {
            description: t('invoice_download_desc', 'Direct MOHRE Sponsor receipt downloaded in PDF format successfully.')
        });
    };

    return (
        <EmployerLayout title={t('sponsor_pass_billing', 'Sponsor Pass & Billing')}>
            <Head title={t('subscription_billing_title', 'Subscription Billing & Invoices - Employer Portal')} />

            <div className="space-y-8 select-none w-full pb-16">
                
                {/* Simulated payment failed retry block */}
                {simulatedFailedState && (
                    <div className="bg-gradient-to-r from-rose-500/10 to-red-600/10 border border-rose-300 rounded-2xl p-5 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 shadow-xs animate-pulse">
                        <div className="flex items-center space-x-3.5">
                            <div className="w-11 h-11 rounded-xl bg-rose-500/20 text-rose-600 flex items-center justify-center flex-shrink-0 border border-rose-200">
                                <AlertCircle className="w-5 h-5" />
                            </div>
                            <div>
                                <h4 className="font-extrabold text-sm text-slate-800">{t('recurrent_billing_failed', 'Your recurrent subscription billing has FAILED!')}</h4>
                                <p className="text-xs text-slate-500 font-medium">{t('recurrent_billing_failed_desc', 'Card renewal failed due to insufficient funds. Retry using PayTabs to avoid profile lockout.')}</p>
                            </div>
                        </div>
                        <button
                            onClick={handleRetryPayment}
                            className="bg-rose-600 hover:bg-rose-700 text-white px-5 py-2.5 rounded-xl text-xs font-black shadow-sm transition-all flex items-center space-x-1.5 shrink-0"
                        >
                            <RefreshCw className="w-3.5 h-3.5 animate-spin" />
                            <span>{t('retry_payment_now', 'Retry Payment Now')}</span>
                        </button>
                    </div>
                )}

                {/* Current Active Plan status banner */}
                <div className="bg-white p-6 rounded-2xl border border-slate-200 shadow-sm flex flex-col sm:flex-row items-start sm:items-center justify-between gap-6">
                    <div className="flex items-center space-x-4">
                        <div className="w-12 h-12 rounded-xl bg-blue-50 text-[#185FA5] flex items-center justify-center font-bold border border-blue-100 flex-shrink-0">
                            <CreditCard className="w-6 h-6" />
                        </div>
                        <div>
                            <div className="text-[10px] font-black text-slate-400 uppercase tracking-widest">{t('active_plan_pass', 'Active Plan Pass')}</div>
                            <h3 className="text-lg font-black text-slate-900 tracking-tight mt-0.5">{activePlan}</h3>
                            <p className="text-xs text-slate-500 font-semibold mt-0.5">
                                {t('renewing_auto_payment_on', 'Renewing via auto-payment on')} <span className="font-bold text-[#185FA5]">{expiresAt}</span>
                            </p>
                        </div>
                    </div>

                    <div className="flex items-center space-x-3.5">
                        <button
                            onClick={triggerFailedPaymentSimulation}
                            className="text-[10px] font-black text-slate-400 hover:text-slate-600 underline"
                            title="Simulate card failure to test retry mechanism"
                        >
                            {t('simulate_billing_failure', 'Simulate Billing Failure')}
                        </button>
                        <div className="flex items-center space-x-1.5 bg-emerald-50 border border-emerald-200 text-emerald-800 px-4 py-2 rounded-xl text-xs font-black">
                            <CheckCircle2 className="w-4 h-4 text-emerald-600" />
                            <span>{t('verified_sponsor_status', 'Verified Sponsor Status')}</span>
                        </div>
                    </div>
                </div>

                {showSuccess && (
                    <div className="p-4 bg-gradient-to-r from-emerald-500 to-emerald-600 text-white rounded-2xl text-xs font-bold flex items-center space-x-2.5 shadow-md animate-fade-in border border-emerald-600">
                        <Sparkles className="w-4 h-4 text-amber-300" />
                        <span>{t('sponsor_pass_updated', 'Sponsor Pass updated successfully! PayTabs transaction logged.')}</span>
                    </div>
                )}

                {/* Available Plan Tiers Pricing Grid */}
                <div className="space-y-4">
                    <div>
                        <h2 className="text-lg font-black text-slate-900 tracking-tight">{t('available_subscription_tiers', 'Available Subscription Tiers')}</h2>
                        <p className="text-xs text-slate-500 mt-0.5 font-medium">{t('available_subscription_tiers_desc', 'Upgrade or cancel anytime. All contracts compliant with UAE Tadbeer MOHRE guides.')}</p>
                    </div>

                    <div className="grid grid-cols-1 md:grid-cols-3 gap-6 pt-2">
                        {plans.map((plan) => {
                            const isCurrent = activePlan.toLowerCase().includes(plan.id.toLowerCase());

                            return (
                                <div
                                    key={plan.id}
                                    className={`bg-white rounded-3xl border shadow-sm flex flex-col justify-between overflow-hidden transition-all relative ${
                                        isCurrent 
                                            ? 'border-[#185FA5] ring-4 ring-[#185FA5]/10 scale-[1.02]' 
                                            : 'border-slate-200 hover:border-slate-300'
                                    }`}
                                >
                                    {plan.popular && (
                                        <div className="bg-[#185FA5] text-white text-[9px] font-black uppercase tracking-wider text-center py-1.5 shadow-xs">
                                            {t('most_popular_tier', 'Most Popular Tier')}
                                        </div>
                                    )}

                                    <div className="p-6 space-y-6 flex-1 flex flex-col justify-between">
                                        <div className="space-y-4">
                                            <div>
                                                <h3 className="font-extrabold text-base text-slate-900">{plan.name}</h3>
                                                <div className="mt-2.5 flex items-baseline space-x-1">
                                                    <span className="text-3xl font-black text-slate-900 tracking-tight">{plan.price}</span>
                                                    <span className="text-xs font-semibold text-slate-400">/ {plan.period}</span>
                                                </div>
                                            </div>

                                            <ul className="space-y-3 pt-5 border-t border-slate-100">
                                                {plan.features.map(f => (
                                                    <li key={f} className="flex items-start space-x-3 text-xs text-slate-600 font-medium">
                                                        <Check className="w-4 h-4 text-emerald-600 flex-shrink-0 mt-0.5" />
                                                        <span>{f}</span>
                                                    </li>
                                                ))}
                                            </ul>
                                        </div>

                                        <button
                                            type="button"
                                            onClick={() => handleSelectPlan(plan)}
                                            className={`w-full h-11 rounded-xl font-bold text-xs flex items-center justify-center transition-all shadow-xs mt-6 ${
                                                isCurrent
                                                    ? 'bg-emerald-600 hover:bg-emerald-700 text-white cursor-default'
                                                    : 'bg-[#185FA5] hover:bg-[#144f8a] text-white'
                                            }`}
                                        >
                                            {isCurrent ? t('current_active_tier', 'Current Active Tier ✓') : t('select_plan_tier', 'Select Plan Tier')}
                                        </button>
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                </div>

                {/* Payment History & Invoice logs */}
                <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 pt-4">
                    {/* Invoice Logs */}
                    <div className="lg:col-span-8 bg-white p-6 rounded-3xl border border-slate-200 shadow-sm space-y-6">
                        <div className="flex items-center justify-between border-b border-slate-100 pb-3">
                            <div className="flex items-center space-x-2">
                                <FileText className="w-5 h-5 text-[#185FA5]" />
                                <h3 className="font-extrabold text-base text-slate-900">{t('billing_payment_receipts', 'Billing Payment Receipts')}</h3>
                            </div>
                            <span className="text-[10px] text-slate-400 font-bold uppercase">{t('tax_compliant_invoices', 'Tax Compliant invoices')}</span>
                        </div>

                        <div className="divide-y divide-slate-100">
                            {invoices.map((inv) => (
                                <div key={inv.id} className="flex items-center justify-between py-4 text-xs font-semibold text-slate-700">
                                    <div className="space-y-1">
                                        <div className="font-bold text-slate-800 flex items-center space-x-1.5">
                                            <span>{inv.plan}</span>
                                            <span className="text-[9px] text-slate-400 font-mono">({inv.id})</span>
                                        </div>
                                        <div className="text-[10px] text-slate-400 font-medium">Billed: {inv.date}</div>
                                    </div>

                                    <div className="flex items-center space-x-6">
                                        <div className="text-right">
                                            <div className="font-extrabold text-slate-900">{inv.amount}</div>
                                            <span className={`text-[9px] font-black uppercase px-2 py-0.5 rounded ${
                                                inv.status === 'Paid' ? 'bg-emerald-50 text-emerald-700' : 'bg-amber-50 text-amber-700'
                                            }`}>
                                                {inv.status}
                                            </span>
                                        </div>

                                        <button
                                            onClick={() => downloadReceipt(inv.id)}
                                            className="p-2 border border-slate-200 hover:bg-slate-50 text-slate-500 rounded-xl transition-colors"
                                            title="Download Tax Receipt"
                                        >
                                            <Download className="w-4 h-4" />
                                        </button>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>

                    {/* Sponsor Billing Details Form */}
                    <div className="lg:col-span-4 bg-white p-6 rounded-3xl border border-slate-200 shadow-sm space-y-6">
                        <div className="space-y-1">
                            <h3 className="font-extrabold text-base text-slate-900">{t('corporate_details', 'Corporate Details')}</h3>
                            <p className="text-xs text-slate-500 font-medium">{t('update_tax_invoicing', 'Update tax invoicing options.')}</p>
                        </div>

                        <div className="space-y-4 text-xs font-bold text-slate-700">
                            <div>
                                <label className="block text-slate-400 uppercase tracking-widest text-[9px] mb-1.5">{t('sponsor_email_address', 'Sponsor Email Address')}</label>
                                <input 
                                    type="email"
                                    value={billingEmail}
                                    onChange={(e) => setBillingEmail(e.target.value)}
                                    className="w-full p-2.5 border border-slate-200 rounded-xl bg-slate-50/50"
                                />
                            </div>

                            <div>
                                <label className="block text-slate-400 uppercase tracking-widest text-[9px] mb-1.5">{t('billing_vat_id', 'Billing VAT Registry ID (Optional)')}</label>
                                <input 
                                    type="text"
                                    placeholder="e.g. TRN 100293810200003"
                                    className="w-full p-2.5 border border-slate-200 rounded-xl bg-slate-50/50"
                                />
                            </div>

                            <button
                                onClick={() => toast.success(t('corporate_billing_updated', 'Corporate billing details updated.'))}
                                className="w-full bg-[#185FA5] hover:bg-[#144f8a] text-white rounded-xl py-2.5 font-bold text-xs"
                            >
                                {t('save_billing_profile', 'Save Billing Profile')}
                            </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">{t('paytabs_secured_checkout', '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">
                                {t('gateway_version', '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">{t('order_description', '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">{t('total_amount', '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">{t('cardholder_name', '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">{t('card_number', '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">{t('expiry_date', '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">{t('security_code', '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>{t('pci_dss_cryptography', '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>{t('authorize_payment', 'Authorize Payment')}</span>
                                <ArrowRight className="w-4 h-4" />
                            </button>
                        </form>
                    </div>
                </div>
            )}

        </EmployerLayout>
    );
}
