import { ClassIcon } from '@/components/game/class-icon';
import { Badge } from '@/components/ui/badge';
import { route } from '@/lib/route-helper';
import { memo, useCallback, useEffect, useState } from 'react';

interface TopSpenderItem {
    id: number;
    rank: number;
    name: string;
    class: number;
    class_name: string;
    amount: number;
}

interface TopSpenderWidgetProps {
    topSpenders: TopSpenderItem[];
    widgetBackgroundUrl?: string | null;
}

const getRankBadgeColor = (rank: number) => {
    if (rank === 1) return 'bg-yellow-100 text-yellow-800 border-yellow-300 dark:bg-yellow-900/60 dark:text-yellow-300 dark:border-yellow-700';
    if (rank === 2) return 'bg-gray-100 text-gray-800 border-gray-300 dark:bg-gray-700/60 dark:text-gray-300 dark:border-gray-600';
    if (rank === 3) return 'bg-orange-100 text-orange-800 border-orange-300 dark:bg-orange-900/60 dark:text-orange-300 dark:border-orange-700';
    return 'bg-blue-100 text-blue-800 border-blue-300 dark:bg-blue-900/60 dark:text-blue-300 dark:border-blue-700';
};

export const TopSpenderWidget = memo(function TopSpenderWidget({ topSpenders: initialTopSpenders, widgetBackgroundUrl }: TopSpenderWidgetProps) {
    const [topSpenders, setTopSpenders] = useState<TopSpenderItem[]>(initialTopSpenders);

    const fetchTopSpenders = useCallback(async () => {
        try {
            const response = await fetch(route('api.topspenders'));
            if (response.ok) {
                const data = await response.json();
                setTopSpenders(data);
            }
        } catch (error) {
            console.error('Failed to fetch top spenders:', error);
        }
    }, []);

    useEffect(() => {
        const interval = setInterval(fetchTopSpenders, 60000);
        return () => clearInterval(interval);
    }, [fetchTopSpenders]);

    return (
        <div
            className="side-block rounded-lg border p-4"
            style={{
                backgroundImage: `url('${widgetBackgroundUrl || '/img/step/bg.webp'}')`,
                backgroundRepeat: 'no-repeat',
                backgroundSize: 'cover',
                backgroundColor: 'transparent',
            }}
        >
            <div className="flex flex-col gap-3">
                {/* Icon and Title */}
                <div className="flex items-center gap-4">
                    <div className="flex-shrink-0">
                        <img
                            src="/img/step/pic-red-pvp.webp"
                            alt="Top Spender Icon"
                            width={159}
                            height={158}
                            className="h-16 w-auto"
                            style={{ filter: 'hue-rotate(50deg)' }}
                        />
                    </div>
                    <h3 className="text-xl font-bold tracking-widest text-white" style={{ fontFamily: 'serif' }}>
                        TOP SPENDER
                    </h3>
                </div>

                {/* Content */}
                <div className="w-full">
                    {topSpenders && topSpenders.length > 0 ? (
                        <div className="overflow-x-auto">
                            <table className="w-full text-sm">
                                <thead>
                                    <tr className="border-b border-white/30">
                                        <th className="px-2 py-2 text-left text-xs font-bold text-white/80 uppercase">Rank</th>
                                        <th className="px-2 py-2 text-left text-xs font-bold text-white/80 uppercase">Player</th>
                                        <th className="px-2 py-2 text-right text-xs font-bold text-white/80 uppercase">Total</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {topSpenders.slice(0, 10).map((player) => (
                                        <tr key={player.id} className="border-b border-white/10 transition-colors hover:bg-white/5">
                                            <td className="px-2 py-3">
                                                <Badge variant="outline" className={getRankBadgeColor(player.rank)}>
                                                    {player.rank}
                                                </Badge>
                                            </td>
                                            <td className="px-2 py-3">
                                                <div className="flex items-center gap-2">
                                                    {player.class !== null && player.class_name && player.class_name !== 'Unknown' && (
                                                        <ClassIcon classId={player.class} size="md" />
                                                    )}
                                                    <span className="font-medium text-white">{player.name}</span>
                                                </div>
                                            </td>
                                            <td className="px-2 py-3 text-right">
                                                <span className="font-semibold text-yellow-400">Rp. {player.amount.toLocaleString('id-ID')}</span>
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    ) : (
                        <div className="py-4 text-center text-white/60">
                            <p className="font-medium">No Top Spenders Yet</p>
                            <p className="text-sm">Be the first to top up!</p>
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
});
