// component/PlayerSearch.tsx
'use client';

import { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import PlayerModal from './PlayerModal';
import { Player } from '../types';
import { searchPlayers } from '../utils/api';
import { toast } from 'react-toastify';

const PlayerSearch: React.FC = () => {
  const [searchTerm, setSearchTerm] = useState<string>('');
  const [players, setPlayers] = useState<Player[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [selectedPlayerId, setSelectedPlayerId] = useState<string | null>(null);
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false);

  const handleSearch = async () => {
    if (!searchTerm.trim()) {
      toast.error("Please enter a search term.");
      setPlayers([]);
      return;
    }

    setLoading(true);
    setPlayers([]);

    try {
      const data = await searchPlayers(searchTerm);
      setPlayers(data);
      if (data.length === 0) {
        toast.info("No players found. Try a different search.");
      }
    } catch (error: any) {
      toast.error(error);
    } finally {
      setLoading(false);
    }
  };

  const handlePlayerClick = (playerId: string) => {
    setSelectedPlayerId(playerId);
    setIsModalOpen(true);
  };

  const handleKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      handleSearch();
    }
  };

  return (
    <div>
      <Card>
        <CardHeader>
          <CardTitle>Player Search</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex flex-col md:flex-row gap-2 mb-4">
            <Input 
              type="text" 
              placeholder="Search players..." 
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              onKeyPress={handleKeyPress}
            />
            <Button onClick={handleSearch} disabled={loading}>
              {loading ? 'Searching...' : 'Search'}
            </Button>
          </div>
          <div className="space-y-4">
            {loading ? (
              <p>Searching...</p>
            ) : (
              players.map(player => (
                <div 
                  key={player.player_id} 
                  className="flex items-center p-4 bg-white rounded shadow hover:bg-gray-100 cursor-pointer"
                  onClick={() => handlePlayerClick(player.player_id)}
                >
                  <Avatar className="mr-4">
                    {player.photo_url ? (
                      <img src={player.photo_url} alt={player.name} />
                    ) : (
                      <AvatarFallback>
                        {player.name.charAt(0)}
                      </AvatarFallback>
                    )}
                  </Avatar>
                  <div>
                    <h3 className="text-lg font-semibold">{player.name}</h3>
                    <p className="text-sm text-gray-500">{player.position} - {player.team}</p>
                  </div>
                </div>
              ))
            )}
          </div>
        </CardContent>
      </Card>

      {/* Player Modal */}
      {selectedPlayerId && (
        <PlayerModal 
          playerId={selectedPlayerId} 
          isOpen={isModalOpen} 
          onClose={() => setIsModalOpen(false)} 
        />
      )}
    </div>
  );
};

export default PlayerSearch;