import React from 'react';
import { motion } from 'motion/react';
import { Trophy, Medal, Star, ArrowRight, Search, Filter } from 'lucide-react';
import { type LeaderboardEntry, type User } from '../types';
import { cn } from '../lib/utils';

interface LeaderboardProps {
  user?: User | null;
}

export function Leaderboard({ user }: LeaderboardProps) {
  const [entries, setEntries] = React.useState<LeaderboardEntry[]>([]);
  const [loading, setLoading] = React.useState(true);
  const [filter, setFilter] = React.useState<string>('all');
  const [search, setSearch] = React.useState('');

  const fetchLeaderboard = async () => {
    try {
      const res = await fetch('/api/leaderboard');
      const data = await res.json();
      setEntries(data);
    } catch (error) {
      console.error('Failed to fetch leaderboard:', error);
    } finally {
      setLoading(false);
    }
  };

  React.useEffect(() => {
    fetchLeaderboard();
  }, []);

  const filteredEntries = entries.filter(e => {
    const matchesFilter = filter === 'all' || e.grade === filter;
    const matchesSearch = e.name.toLowerCase().includes(search.toLowerCase()) || 
                         e.rollNumber.toLowerCase().includes(search.toLowerCase());
    return matchesFilter && matchesSearch;
  });

  const grades = Array.from(new Set(entries.map(e => e.grade))).sort();

  return (
    <div className="space-y-10">
      <div className="text-center max-w-2xl mx-auto">
        <h2 className="text-4xl font-black text-white mb-4">Class Leaderboard 🏆</h2>
        <p className="text-slate-400">Celebrate the top performers of RS Learning Lab. Keep learning to climb the ranks!</p>
      </div>

      <div className="bg-dark-card rounded-3xl border border-dark-border overflow-hidden shadow-2xl">
        <div className="p-6 border-b border-dark-border flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 bg-slate-800/30">
          <div className="relative w-full sm:w-64">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-500" size={18} />
            <input 
              type="text"
              placeholder="Search students..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="w-full pl-10 pr-4 py-2 rounded-xl bg-dark-bg border border-dark-border text-white text-sm focus:ring-2 focus:ring-[#0b8c9f] outline-none"
            />
          </div>
          <div className="flex items-center gap-2">
            <Filter size={18} className="text-slate-500" />
            <select 
              value={filter}
              onChange={(e) => setFilter(e.target.value)}
              className="bg-dark-bg border border-dark-border text-white text-sm rounded-xl px-3 py-2 outline-none focus:ring-2 focus:ring-[#0b8c9f]"
            >
              <option value="all">All Classes</option>
              {grades.map(g => <option key={g} value={g}>{g}</option>)}
            </select>
          </div>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full text-left">
            <thead>
              <tr className="bg-slate-800/50 border-b border-dark-border">
                <th className="px-8 py-4 text-xs font-bold text-slate-500 uppercase tracking-widest">Rank</th>
                <th className="px-8 py-4 text-xs font-bold text-slate-500 uppercase tracking-widest">Student</th>
                <th className="px-8 py-4 text-xs font-bold text-slate-500 uppercase tracking-widest">Class</th>
                <th className="px-8 py-4 text-xs font-bold text-slate-500 uppercase tracking-widest">Recognition</th>
                {user?.role === 'teacher' && (
                  <th className="px-8 py-4 text-xs font-bold text-slate-500 uppercase tracking-widest text-right">Learning Effective Index (LEI)</th>
                )}
              </tr>
            </thead>
            <tbody className="divide-y divide-dark-border">
              {loading ? (
                <tr><td colSpan={user?.role === 'teacher' ? 5 : 4} className="px-8 py-12 text-center text-slate-500">Loading leaderboard...</td></tr>
              ) : filteredEntries.length === 0 ? (
                <tr><td colSpan={user?.role === 'teacher' ? 5 : 4} className="px-8 py-12 text-center text-slate-500">No entries found.</td></tr>
              ) : (
                filteredEntries.map((entry, index) => (
                  <motion.tr 
                    key={entry.rollNumber}
                    initial={{ opacity: 0, y: 10 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: index * 0.05 }}
                    className={cn(
                      "group hover:bg-slate-800/50 transition-all",
                      index === 0 && "bg-yellow-500/5",
                      index === 1 && "bg-slate-400/5",
                      index === 2 && "bg-orange-500/5"
                    )}
                  >
                    <td className="px-8 py-6">
                      <div className="flex items-center gap-3">
                        {index === 0 ? (
                          <div className="w-8 h-8 bg-yellow-500 rounded-lg flex items-center justify-center text-white shadow-lg shadow-yellow-500/20">
                            <Trophy size={16} />
                          </div>
                        ) : index === 1 ? (
                          <div className="w-8 h-8 bg-slate-400 rounded-lg flex items-center justify-center text-white shadow-lg shadow-slate-400/20">
                            <Medal size={16} />
                          </div>
                        ) : index === 2 ? (
                          <div className="w-8 h-8 bg-orange-500 rounded-lg flex items-center justify-center text-white shadow-lg shadow-orange-500/20">
                            <Medal size={16} />
                          </div>
                        ) : (
                          <span className="w-8 h-8 flex items-center justify-center font-bold text-slate-500">{index + 1}</span>
                        )}
                      </div>
                    </td>
                    <td className="px-8 py-6">
                      <div className="flex items-center gap-4">
                        <div className="w-10 h-10 bg-slate-800 rounded-full flex items-center justify-center text-white font-bold text-sm">
                          {entry.name.charAt(0)}
                        </div>
                        <span className="font-bold text-white group-hover:text-[#0b8c9f] transition-colors">{entry.name}</span>
                      </div>
                    </td>
                    <td className="px-8 py-6 text-slate-400 font-medium">{entry.grade}</td>
                    <td className="px-8 py-6">
                      <span className="px-3 py-1 rounded-full bg-[#0b8c9f]/10 text-[#0b8c9f] text-[10px] font-bold uppercase tracking-widest border border-[#0b8c9f]/20">
                        {entry.label || 'Active Learner'}
                      </span>
                    </td>
                    {user?.role === 'teacher' && (
                      <td className="px-8 py-6 text-right">
                        <div className="flex items-center justify-end gap-2">
                          <Star size={16} className="text-[#ff7a00]" fill="#ff7a00" />
                          <span className="text-xl font-black text-white">{entry.lei}</span>
                        </div>
                      </td>
                    )}
                  </motion.tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
