'use client';

import { useState, useEffect } from 'react';
import { createClient } from '@/lib/supabase/client';
import { Sparkles, Zap, Crown, Star, Gift } from 'lucide-react';

interface UserStatus {
    credits: number;
    planName: string;
    planDisplayName: string;
}

const PLAN_ICONS: Record<string, { icon: React.ReactNode; color: string }> = {
    starter: { icon: <Gift size={12} />, color: 'text-zinc-400 border-zinc-600' },
    bronze: { icon: <Star size={12} />, color: 'text-amber-600 border-amber-600/50' },
    silver: { icon: <Zap size={12} />, color: 'text-zinc-300 border-zinc-400' },
    gold: { icon: <Crown size={12} />, color: 'text-yellow-500 border-yellow-500/50' },
};

export default function UserStatusBadge() {
    const [status, setStatus] = useState<UserStatus | null>(null);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        loadStatus();
    }, []);

    const loadStatus = async () => {
        try {
            const supabase = createClient();
            const { data: { user } } = await supabase.auth.getUser();

            if (!user) {
                setLoading(false);
                return;
            }

            // Get credits
            const { data: credits } = await supabase
                .from('user_credits')
                .select('balance')
                .eq('user_id', user.id)
                .single();

            // Get subscription plan with monthly credits
            const { data: subscription } = await supabase
                .from('user_subscriptions')
                .select(`
                    plan_id,
                    subscription_plans (
                        name,
                        display_name,
                        monthly_credits
                    )
                `)
                .eq('user_id', user.id)
                .single();

            // Extract plan from joined data
            const planData = subscription?.subscription_plans;
            const plan = Array.isArray(planData) ? planData[0] : planData;

            // If no credits entry yet, show plan's monthly credits as expected amount
            const displayCredits = credits?.balance ?? plan?.monthly_credits ?? 10;

            setStatus({
                credits: displayCredits,
                planName: plan?.name ?? 'starter',
                planDisplayName: plan?.display_name ?? 'Starter',
            });
        } catch (error) {
            console.error('[UserStatusBadge] Error loading status:', error);
        } finally {
            setLoading(false);
        }
    };

    if (loading || !status) {
        return null;
    }

    const planConfig = PLAN_ICONS[status.planName] || PLAN_ICONS.starter;

    return (
        <div className="flex items-center gap-2">
            {/* Plan Badge */}
            <div className={`flex items-center gap-1.5 px-2.5 py-1 rounded-full border bg-zinc-900/50 ${planConfig.color}`}>
                {planConfig.icon}
                <span className="text-[10px] font-bold uppercase tracking-wider">
                    {status.planDisplayName}
                </span>
            </div>

            {/* Credits */}
            <div className="flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-orange-600/30 bg-orange-950/20">
                <Sparkles size={12} className="text-orange-500" />
                <span className="text-[10px] font-bold text-orange-400">
                    {status.credits}
                </span>
            </div>
        </div>
    );
}
