import React, { useState, useEffect } from 'react';
import { Player } from '../types';
import { dbService } from '../services/DatabaseService';

interface PlayersProps {
  onSelectPlayer: (id: string) => void;
}

const Players: React.FC<PlayersProps> = ({ onSelectPlayer }) => {
  const [players, setPlayers] = useState<Player[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const loadData = async () => {
      setLoading(true);
      try {
        await dbService.fetchAll();
      } catch (error) {
        console.warn('Failed to fetch fresh data:', error);
        // Continue with cached data
      }
      setLoading(false);
    };

    // Subscribe to database updates
    const unsubDb = dbService.subscribe(() => {
      setPlayers(dbService.getPlayers());
    });

    // Load fresh data on mount
    loadData();

    return unsubDb;
  }, []);

  return (
    <div className="animate-in fade-in">
       <div className="flex justify-between items-center mb-6">
         <h2 className="text-2xl font-bold">Bürgerverzeichnis</h2>
         <div className="relative">
            <input
              type="text"
              placeholder="Filtern nach Tag oder Name..."
              className="bg-surfaceHighlight border border-border rounded-lg pl-10 pr-4 py-2 text-sm text-textMain focus:border-accentInfo focus:outline-none w-64 transition-colors"
            />
         </div>
       </div>

       {loading ? (
         <div className="flex justify-center py-20">
           <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-accentInfo"></div>
         </div>
       ) : (
         <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
           {players.map(player => (
             <div
               key={player.uuid}
               onClick={() => onSelectPlayer(player.uuid)}
               className="group bg-surface border border-border p-4 rounded-xl cursor-pointer hover:border-accentInfo/50 transition-all duration-200 hover:shadow-card"
             >
               <div className="flex items-center gap-4">
                 <div className="w-12 h-12 rounded-md flex items-center justify-center font-bold text-lg text-textMuted group-hover:text-textMain transition-colors">
                   <img src={"https://minotar.net/armor/bust/"+player.username+"/500.png"}></img>
                 </div>
                 <div>
                   <div className="font-semibold text-textMain group-hover:text-accentInfo transition-colors">{player.username}</div>
                   <div className="text-xs text-textMuted mt-1 flex gap-2">
                      {player.tags.slice(0, 2).map(t => <span key={t}>{t}</span>)}
                   </div>
                 </div>
               </div>
             </div>
           ))}
         </div>
       )}
    </div>
  );
};

export default Players;
