import { Link, usePage } from '@inertiajs/react';
import { useState } from 'react';
import { Zap, X, ArrowRight, Lock, AlertTriangle, Clock } from 'lucide-react';

/**
 * Compact sidebar card — permanent for Basic users (no dismiss).
 */
export function SidebarUpgradeCard() {
    const { auth } = usePage().props;
    if (auth?.subscription?.plan?.slug !== 'basic') return null;

    return (
        <div className="mx-3 mb-3 rounded-xl bg-gradient-to-br from-blue-600 to-indigo-700 p-3.5 text-white">
            <div className="flex items-center gap-2 mb-2">
                <div className="w-6 h-6 bg-white/20 rounded-lg flex items-center justify-center flex-shrink-0">
                    <Zap className="w-3.5 h-3.5 text-yellow-300" />
                </div>
                <p className="text-xs font-bold leading-tight">Unlock Standard</p>
            </div>
            <p className="text-[11px] text-blue-200 mb-3 leading-snug">
                Unlimited invoices + PDF, inventory, vendors, full reports & more.
            </p>
            <Link
                href="/dashboard/subscription"
                className="flex items-center justify-center gap-1.5 w-full py-1.5 bg-white text-blue-700 text-[11px] font-bold rounded-lg hover:bg-blue-50 transition-colors">
                Upgrade — ₦9,500/mo <ArrowRight className="w-3 h-3" />
            </Link>
            <p className="text-[10px] text-blue-300 text-center mt-1.5">14-day free trial · No card needed</p>
        </div>
    );
}

/**
 * Top-of-page subscription status bar.
 * Shows for Basic (upgrade nudge) and for expiring/expired paid plans.
 * Rendered inside AppLayout just above the main content.
 */
export function SubscriptionStatusBar() {
    const { auth, plan_usage } = usePage().props;
    const sub  = auth?.subscription;
    const plan = sub?.plan?.slug ?? 'basic';

    const txPct   = plan_usage?.transactions?.limit > 0 ? (plan_usage.transactions.used / plan_usage.transactions.limit) * 100 : 0;
    const invPct  = plan_usage?.invoices?.limit > 0     ? (plan_usage.invoices.used / plan_usage.invoices.limit) * 100 : 0;
    const custPct = plan_usage?.customers?.limit > 0    ? (plan_usage.customers.used / plan_usage.customers.limit) * 100 : 0;
    const atLimit = txPct >= 100 || invPct >= 100 || custPct >= 100;
    const nearLimit = txPct >= 70 || invPct >= 70 || custPct >= 70;

    // Expiring soon (paid plans only)
    if (plan !== 'basic' && sub?.expiring_soon) {
        const days = sub.days_left;
        return (
            <div className="bg-amber-50 border-b border-amber-200 px-5 py-2.5 flex items-center justify-between gap-3 text-sm flex-shrink-0">
                <div className="flex items-center gap-2 text-amber-800">
                    <Clock className="w-4 h-4 text-amber-500 flex-shrink-0" />
                    <span className="font-semibold">
                        Your {sub.plan.name} plan expires in {days} day{days !== 1 ? 's' : ''}.
                    </span>
                    <span className="text-amber-600 hidden sm:inline">Renew now to avoid being downgraded to Basic.</span>
                </div>
                <Link href="/dashboard/subscription"
                    className="flex items-center gap-1 px-3 py-1 bg-amber-500 text-white text-xs font-bold rounded-lg hover:bg-amber-600 transition-colors whitespace-nowrap flex-shrink-0">
                    Renew <ArrowRight className="w-3 h-3" />
                </Link>
            </div>
        );
    }

    // Basic — at limit
    if (plan === 'basic' && atLimit) {
        const resource = txPct >= 100 ? 'transactions' : invPct >= 100 ? 'invoices' : 'customers';
        return (
            <div className="bg-red-50 border-b border-red-200 px-5 py-2.5 flex items-center justify-between gap-3 text-sm flex-shrink-0">
                <div className="flex items-center gap-2 text-red-800">
                    <Lock className="w-4 h-4 text-red-500 flex-shrink-0" />
                    <span className="font-semibold">
                        You've used all your {resource} for this month.
                    </span>
                    <span className="text-red-600 hidden sm:inline">Upgrade to Standard to continue without limits.</span>
                </div>
                <Link href="/dashboard/subscription"
                    className="flex items-center gap-1 px-3 py-1 bg-red-600 text-white text-xs font-bold rounded-lg hover:bg-red-700 transition-colors whitespace-nowrap flex-shrink-0">
                    Upgrade <ArrowRight className="w-3 h-3" />
                </Link>
            </div>
        );
    }

    // Basic — near limit
    if (plan === 'basic' && nearLimit) {
        const resource = txPct >= 70 ? 'transactions' : invPct >= 70 ? 'invoices' : 'customers';
        return (
            <div className="bg-amber-50 border-b border-amber-200 px-5 py-2.5 flex items-center justify-between gap-3 text-sm flex-shrink-0">
                <div className="flex items-center gap-2 text-amber-800">
                    <AlertTriangle className="w-4 h-4 text-amber-500 flex-shrink-0" />
                    <span className="font-semibold">Approaching your {resource} limit.</span>
                    <span className="text-amber-600 hidden sm:inline">Upgrade to Standard for unlimited access.</span>
                </div>
                <Link href="/dashboard/subscription"
                    className="flex items-center gap-1 px-3 py-1 bg-amber-500 text-white text-xs font-bold rounded-lg hover:bg-amber-600 transition-colors whitespace-nowrap flex-shrink-0">
                    See Plans <ArrowRight className="w-3 h-3" />
                </Link>
            </div>
        );
    }

    // Basic — default always-on nudge strip
    if (plan === 'basic') {
        return (
            <div className="bg-gradient-to-r from-blue-600 to-indigo-700 px-5 py-2 flex items-center justify-between gap-3 flex-shrink-0">
                <div className="flex items-center gap-2 text-white">
                    <Zap className="w-3.5 h-3.5 text-yellow-300 flex-shrink-0" />
                    <span className="text-xs font-semibold">You're on the Basic (free) plan.</span>
                    <span className="text-blue-200 text-xs hidden md:inline">Unlock unlimited invoices, PDF, inventory, vendors & reports.</span>
                </div>
                <Link href="/dashboard/subscription"
                    className="flex items-center gap-1 px-3 py-1 bg-white text-blue-700 text-xs font-bold rounded-lg hover:bg-blue-50 transition-colors whitespace-nowrap flex-shrink-0">
                    Upgrade — ₦9,500/mo <ArrowRight className="w-3 h-3" />
                </Link>
            </div>
        );
    }

    return null;
}

/**
 * Dashboard contextual banner — only shown on the /dashboard page, dismissible per session.
 */
export function DashboardUpgradeBanner({ usage }) {
    const { auth } = usePage().props;
    const [dismissed, setDismissed] = useState(
        () => typeof sessionStorage !== 'undefined' && sessionStorage.getItem('upgrade_banner_dismissed') === '1'
    );

    if (auth?.subscription?.plan?.slug !== 'basic') return null;
    if (dismissed) return null;

    const txPct   = usage?.transactions?.limit > 0 ? (usage.transactions.used / usage.transactions.limit) * 100 : 0;
    const invPct  = usage?.invoices?.limit > 0     ? (usage.invoices.used / usage.invoices.limit) * 100 : 0;
    const custPct = usage?.customers?.limit > 0    ? (usage.customers.used / usage.customers.limit) * 100 : 0;
    const nearLimit = txPct >= 70 || invPct >= 70 || custPct >= 70;

    const dismiss = () => {
        sessionStorage.setItem('upgrade_banner_dismissed', '1');
        setDismissed(true);
    };

    if (!nearLimit) return null; // Default nudge already in the status bar; only show dashboard card when relevant

    const resource = txPct >= 70 ? 'transactions' : invPct >= 70 ? 'invoices' : 'customers';
    const atLimit  = txPct >= 100 || invPct >= 100 || custPct >= 100;

    return (
        <div className={`rounded-2xl p-4 flex items-start gap-4 ${atLimit ? 'bg-red-50 border border-red-200' : 'bg-amber-50 border border-amber-200'}`}>
            <div className={`w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0 ${atLimit ? 'bg-red-100' : 'bg-amber-100'}`}>
                {atLimit ? <Lock className="w-5 h-5 text-red-500" /> : <AlertTriangle className="w-5 h-5 text-amber-500" />}
            </div>
            <div className="flex-1 min-w-0">
                <p className={`text-sm font-bold ${atLimit ? 'text-red-800' : 'text-amber-800'}`}>
                    {atLimit ? `You've hit your ${resource} limit for this month` : `You're approaching your ${resource} limit`}
                </p>
                <p className={`text-xs mt-0.5 ${atLimit ? 'text-red-600' : 'text-amber-700'}`}>
                    Upgrade to Standard for unlimited {resource}, PDF invoices, inventory tracking, and more — starting at ₦9,500/mo with a 14-day free trial.
                </p>
            </div>
            <div className="flex items-center gap-2 flex-shrink-0">
                <Link href="/dashboard/subscription"
                    className={`flex items-center gap-1.5 px-4 py-2 text-white text-xs font-bold rounded-xl transition-colors whitespace-nowrap ${atLimit ? 'bg-red-600 hover:bg-red-700' : 'bg-amber-500 hover:bg-amber-600'}`}>
                    Upgrade Now <ArrowRight className="w-3 h-3" />
                </Link>
                <button onClick={dismiss} className={`p-1.5 rounded-lg ${atLimit ? 'hover:bg-red-100 text-red-400' : 'hover:bg-amber-100 text-amber-400'}`}>
                    <X className="w-4 h-4" />
                </button>
            </div>
        </div>
    );
}

/**
 * Inline lock badge for locked nav items.
 */
export function LockedBadge({ plan = 'Standard' }) {
    return (
        <span className="inline-flex items-center gap-1 ml-1 px-1.5 py-0.5 bg-blue-100 text-blue-600 text-[9px] font-bold rounded-full uppercase tracking-wide">
            <Lock className="w-2.5 h-2.5" /> {plan}
        </span>
    );
}
