// 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 { Player } from '../types';
import { searchPlayers } from '../utils/api';
import { toast } from 'react-toastify';
import Link from 'next/link';
import Image from 'next/image';

const PlayerSearch: React.FC = () => {
  const [searchTerm, setSearchTerm] = useState('');
  const [players, setPlayers] = useState<Player[]>([]);
  const [loading, setLoading] = useState(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.message || 'Error searching players.');
    } finally {
      setLoading(false);
    }
  };

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

  return (
    <div className="p-4">
      <Card>
        <CardHeader>
          <CardTitle>Player Search</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex items-center space-x-2">
            <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="mt-4 grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
            {players.map(player => (
              <Link href={`/players/${player.player_id}`} key={player.player_id} className="cursor-pointer hover:shadow-lg transition-shadow">
         <Card>
        <CardContent className="flex flex-col items-center">
      <Avatar className="h-24 w-24 mb-2 relative">
        {player.photo_url ? (
          <Image 
            src={player.photo_url} 
            alt={player.name} 
            fill
            className="rounded-full object-cover" 
          />
        ) : (
          <AvatarFallback>{player.name.charAt(0)}</AvatarFallback>
        )}
      </Avatar>
      <h3 className="text-lg font-semibold">{player.name}</h3>
      <p className="text-sm text-gray-500">{player.position} - {player.team}</p>
                    </CardContent>
                </Card>
            </Link>
            ))}
          </div>
        </CardContent>
      </Card>
    </div>
  );
};

export default PlayerSearch;
// app/players/[id]/page.tsx
'use client';

import React, { useEffect, useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { getPlayerDetails, getPlayerMatches } from '../../../utils/api';
import { Player, Match } from '../../../types';
import Navbar from '../../../component/Navbar';
import Link from 'next/link';
import { Avatar, AvatarFallback } from '../../../components/ui/avatar';
import { Button } from '../../../components/ui/button';
import { FaTwitter, FaFacebook, FaInstagram } from 'react-icons/fa';
import { toast } from 'react-toastify';

const PlayerPage: React.FC = () => {
  const router = useRouter();
  const params = useParams();
  const { id } = params;
  const [player, setPlayer] = useState<Player | null>(null);
  const [matches, setMatches] = useState<Match[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    if (!id) {
      router.push('/');
      return;
    }

    const fetchData = async () => {
      try {
        const fetchedPlayer = await getPlayerDetails(id);
        setPlayer(fetchedPlayer);
        const fetchedMatches = await getPlayerMatches(id, 5);
        setMatches(fetchedMatches);
      } catch (err: any) {
        setError(err.message || 'An error occurred while fetching player data.');
        toast.error(err.message || 'Error fetching player data.');
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [id, router]);

  if (loading) {
    return (
      <>
        <Navbar />
        <div className="flex justify-center items-center h-screen">
          <p className="text-xl">Loading player details...</p>
        </div>
      </>
    );
  }

  if (error || !player) {
  return (
    <>
      <Navbar />
      <div className="flex flex-col justify-center items-center h-screen">
        <p className="text-xl text-red-500">{error || 'Player not found.'}</p>
        <Link href="/" className="mt-4 text-blue-500 underline">
          Go Back Home
        </Link>
      </div>
    </>
  );
 }

  return (
    <>
      <Navbar />
      <div className="container mx-auto p-4">
        <div className="flex flex-col md:flex-row items-start md:items-center space-y-4 md:space-y-0 md:space-x-6">
          <Avatar className="h-40 w-40">
            {player.photo_url ? (
              <img src={player.photo_url} alt={player.name} className="rounded-full object-cover h-full w-full" />
            ) : (
              <AvatarFallback>{player.name.charAt(0)}</AvatarFallback>
            )}
          </Avatar>
          <div>
            <h1 className="text-3xl font-bold">{player.name}</h1>
            <p className="text-lg text-gray-600">{player.position}</p>
            <div className="flex space-x-3 mt-2">
              {player.social?.twitter && (
                <a href={`https://twitter.com/${player.social.twitter}`} target="_blank" rel="noopener noreferrer">
                  <FaTwitter className="h-6 w-6 text-blue-400 hover:text-blue-600" />
                </a>
              )}
              {player.social?.facebook && (
                <a href={`https://facebook.com/${player.social.facebook}`} target="_blank" rel="noopener noreferrer">
                  <FaFacebook className="h-6 w-6 text-blue-600 hover:text-blue-800" />
                </a>
              )}
              {player.social?.instagram && (
              <a  href={`https://instagram.com/${player.social.instagram.replace(/^(https?:\/\/)?(www\.)?instagram\.com\//, '')}`} target="_blank"  rel="noopener noreferrer">
                <FaInstagram className="h-6 w-6 text-pink-500 hover:text-pink-700" />
              </a>
              )}
            </div>
          </div>
        </div>

        <div className="mt-8">
          <h2 className="text-2xl font-semibold">Player Information</h2>
          <div className="mt-4 grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <p><strong>Nationality:</strong> {player.nationality || 'N/A'}</p>
              <p><strong>Team:</strong> {player.team || 'N/A'}</p>
              <p><strong>League:</strong> {player.league || 'N/A'}</p>
              <p><strong>Birthday:</strong> {player.birthday || 'N/A'}</p>
            </div>
            <div>
              <p><strong>Height:</strong> {player.height || 'N/A'}</p>
              <p><strong>Weight:</strong> {player.weight || 'N/A'}</p>
              <p><strong>Jersey Number:</strong> {player.jerseyNumber || 'N/A'}</p>
            </div>
          </div>
        </div>

        <div className="mt-8">
          <h2 className="text-2xl font-semibold">Description</h2>
          <p className="mt-2 text-gray-700">{player.description || 'No description available.'}</p>
        </div>

        <div className="mt-8">
          <Button onClick={() => router.push(`/players/${id}/matches`)} className="bg-blue-500 hover:bg-blue-600">
            View Recent Matches
          </Button>
        </div>

        <div className="mt-16">
          <h2 className="text-2xl font-semibold">Recent Matches</h2>
          {matches.length === 0 ? (
            <p className="mt-2 text-gray-600">No recent matches found.</p>
          ) : (
            <div className="mt-4 space-y-4">
              {matches.map(match => (
                <div key={match.event_id} className="p-4 border rounded-md shadow-sm">
                  <p className="text-lg"><strong>{match.homeTeam}</strong> vs <strong>{match.awayTeam}</strong></p>
                  <p className="text-sm text-gray-600">{match.date} at {match.time}</p>
                  <p className="mt-1">Score: {match.homeScore !== null && match.awayScore !== null ? `${match.homeScore} - ${match.awayScore}` : 'N/A'}</p>
                  <p>Status: {match.status}</p>
                  <p>League: {match.league}</p>
                  <p>Season: {match.season}</p>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </>
  );
};

export default PlayerPage;
// app/league/page.tsx

'use client'; // Retain if interactivity is required; otherwise, consider Server Components

import React, { useState, useEffect } from 'react';
import { useSearchParams } from 'next/navigation';
import Image from 'next/image';
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { AlertCircle } from 'lucide-react';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Button } from "@/components/ui/button";
import Link from 'next/link';

// Interfaces
interface Team { /* ... */ }
interface League { /* ... */ }
interface Standing { /* ... */ }
interface TopScorer { /* ... */ }
interface Match { /* ... */ }
interface LeagueData { /* ... */ }

export default function LeaguePage() {
  const searchParams = useSearchParams();
  const code = searchParams.get('code')?.toUpperCase(); // Get 'code' from query parameters and ensure it's uppercase
  const [leagueData, setLeagueData] = useState<LeagueData | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [activeTab, setActiveTab] = useState<'Teams' | 'Standings' | 'Top Scorers' | 'Matches'>('Teams');

  useEffect(() => {
    const fetchLeagueData = async () => {
      try {
        if (!code) {
          throw new Error('No league code provided');
        }
        const response = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/league/${code}`); // Use environment variable
        if (!response.ok) {
          if (response.status === 404) {
            throw new Error('League not found');
          }
          throw new Error('Failed to fetch league data');
        }
        const data: LeagueData = await response.json();
        setLeagueData(data);
      } catch (error) {
        console.error('Error fetching league data:', error);
        setError(error instanceof Error ? error.message : 'An error occurred');
      } finally {
        setIsLoading(false);
      }
    };

    if (code) {
      fetchLeagueData();
    } else {
      setIsLoading(false);
      setError('No league code provided');
    }
  }, [code]);

  if (isLoading) {
    return <LeagueSkeleton />;
  }

  if (error) {
    return (
      <Alert variant="destructive">
        <AlertCircle className="h-4 w-4" />
        <AlertTitle>Error</AlertTitle>
        <AlertDescription>{error}</AlertDescription>
      </Alert>
    );
  }

  if (!leagueData) {
    return (
      <Alert variant="destructive">
        <AlertCircle className="h-4 w-4" />
        <AlertTitle>Not Found</AlertTitle>
        <AlertDescription>League not found</AlertDescription>
      </Alert>
    );
  }

  const { league, teams, standings, topScorers, matches } = leagueData;

  return (
    <div className="container mx-auto px-4 py-8">
      {/* League Information Card */}
      <Card className="mb-8">
        <CardHeader className="flex flex-row items-center space-x-4">
          <div className="relative w-16 h-16">
            <Image
              src={league.emblem}
              alt={`${league.name} emblem`}
              width={64}
              height={64}
              className="rounded-full object-contain"
              onError={(e) => {
                const target = e.target as HTMLImageElement;
                target.src = '/placeholder.svg';
              }}
            />
          </div>
          <div>
            <CardTitle>{league.name}</CardTitle>
            <p className="text-sm text-gray-500">{league.area.name}</p>
          </div>
        </CardHeader>
        <CardContent>
          <p><strong>Current Season:</strong> {league.currentSeason.startDate} to {league.currentSeason.endDate}</p>
          <p><strong>Current Matchday:</strong> {league.currentSeason.currentMatchday}</p>
        </CardContent>
      </Card>

      {/* Tabs Navigation */}
      <div className="mb-6 flex space-x-4" role="tablist" aria-label="League Data Tabs">
        <Button
          variant={activeTab === 'Teams' ? 'default' : 'outline'}
          onClick={() => setActiveTab('Teams')}
          aria-selected={activeTab === 'Teams'}
          role="tab"
        >
          Teams
        </Button>
        <Button
          variant={activeTab === 'Standings' ? 'default' : 'outline'}
          onClick={() => setActiveTab('Standings')}
          aria-selected={activeTab === 'Standings'}
          role="tab"
        >
          Standings
        </Button>
        <Button
          variant={activeTab === 'Top Scorers' ? 'default' : 'outline'}
          onClick={() => setActiveTab('Top Scorers')}
          aria-selected={activeTab === 'Top Scorers'}
          role="tab"
        >
          Top Scorers
        </Button>
        <Button
          variant={activeTab === 'Matches' ? 'default' : 'outline'}
          onClick={() => setActiveTab('Matches')}
          aria-selected={activeTab === 'Matches'}
          role="tab"
        >
          Matches
        </Button>
      </div>

      {/* Conditional Rendering Based on Active Tab */}
      {activeTab === 'Teams' && (
        <>
          <h2 className="text-2xl font-bold mb-4">Teams</h2>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {teams.map((team) => (
              <Card key={team.id} className="shadow-md">
                <CardHeader className="flex flex-row items-center space-x-4">
                  <div className="relative w-12 h-12">
                    <Image
                      src={team.crest}
                      alt={`${team.name} crest`}
                      width={48}
                      height={48}
                      className="rounded-full object-contain"
                      onError={(e) => {
                        const target = e.target as HTMLImageElement;
                        target.src = '/placeholder.svg';
                      }}
                    />
                  </div>
                  <CardTitle className="text-lg">{team.name}</CardTitle>
                </CardHeader>
                <CardContent>
                  <p><strong>Venue:</strong> {team.venue}</p>
                  <p><strong>Founded:</strong> {team.founded}</p>
                  <p><strong>Club Colors:</strong> {team.clubColors}</p>
                </CardContent>
              </Card>
            ))}
          </div>
        </>
      )}

      {activeTab === 'Standings' && (
        <>
          <h2 className="text-2xl font-bold mb-4">Standings</h2>
          <div className="overflow-x-auto">
            <Table className="min-w-full">
              <TableHeader>
                <TableRow>
                  <TableHead className="px-6 py-3">Pos</TableHead>
                  <TableHead className="px-6 py-3">Team</TableHead>
                  <TableHead className="px-6 py-3">P</TableHead>
                  <TableHead className="px-6 py-3">W</TableHead>
                  <TableHead className="px-6 py-3">D</TableHead>
                  <TableHead className="px-6 py-3">L</TableHead>
                  <TableHead className="px-6 py-3">GF</TableHead>
                  <TableHead className="px-6 py-3">GA</TableHead>
                  <TableHead className="px-6 py-3">GD</TableHead>
                  <TableHead className="px-6 py-3">Pts</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {standings.map((standing) => (
                  <TableRow key={standing.position}>
                    <TableCell className="px-6 py-4">{standing.position}</TableCell>
                    <TableCell className="px-6 py-4 flex items-center space-x-2">
                      <Image
                        src={standing.team.crest}
                        alt={`${standing.team.name} crest`}
                        width={24}
                        height={24}
                        className="rounded-full object-contain"
                        onError={(e) => {
                          const target = e.target as HTMLImageElement;
                          target.src = '/placeholder.svg';
                        }}
                      />
                      <span>{standing.team.name}</span>
                    </TableCell>
                    <TableCell className="px-6 py-4">{standing.playedGames}</TableCell>
                    <TableCell className="px-6 py-4">{standing.won}</TableCell>
                    <TableCell className="px-6 py-4">{standing.draw}</TableCell>
                    <TableCell className="px-6 py-4">{standing.lost}</TableCell>
                    <TableCell className="px-6 py-4">{standing.goalsFor}</TableCell>
                    <TableCell className="px-6 py-4">{standing.goalsAgainst}</TableCell>
                    <TableCell className="px-6 py-4">{standing.goalDifference}</TableCell>
                    <TableCell className="px-6 py-4">{standing.points}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
        </>
      )}

      {activeTab === 'Top Scorers' && (
        <>
          <h2 className="text-2xl font-bold mb-4">Top Scorers</h2>
          <div className="overflow-x-auto">
            <Table className="min-w-full">
              <TableHeader>
                <TableRow>
                  <TableHead className="px-6 py-3">#</TableHead>
                  <TableHead className="px-6 py-3">Player</TableHead>
                  <TableHead className="px-6 py-3">Team</TableHead>
                  <TableHead className="px-6 py-3">Goals</TableHead>
                  <TableHead className="px-6 py-3">Assists</TableHead>
                  <TableHead className="px-6 py-3">Penalties</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {topScorers.map((scorer, index) => (
                  <TableRow key={scorer.player.id}>
                    <TableCell className="px-6 py-4">{index + 1}</TableCell>
                    <TableCell className="px-6 py-4 flex items-center space-x-2">
                      <Image
                        src={scorer.team.crest}
                        alt={`${scorer.team.name} crest`}
                        width={24}
                        height={24}
                        className="rounded-full object-contain"
                        onError={(e) => {
                          const target = e.target as HTMLImageElement;
                          target.src = '/placeholder.svg';
                        }}
                      />
                      <Link
                        href={`/players/?query=${scorer.player.name}`}
                        className="text-blue-500 hover:underline"
                      >
                        {scorer.player.name}
                      </Link>
                    </TableCell>
                    <TableCell className="px-6 py-4">{scorer.team.name}</TableCell>
                    <TableCell className="px-6 py-4">{scorer.goals}</TableCell>
                    <TableCell className="px-6 py-4">{scorer.assists}</TableCell>
                    <TableCell className="px-6 py-4">{scorer.penalties}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
        </>
      )}

      {activeTab === 'Matches' && (
        <>
          <h2 className="text-2xl font-bold mb-4">Upcoming Matches</h2>
          <div className="overflow-x-auto">
            <Table className="min-w-full">
              <TableHeader>
                <TableRow>
                  {/* <TableHead className="px-6 py-3">Match ID</TableHead> */}
                  <TableHead className="px-6 py-3">Date</TableHead>
                  <TableHead className="px-6 py-3">Status</TableHead>
                  <TableHead className="px-6 py-3">Matchday</TableHead>
                  <TableHead className="px-6 py-3">Home Team</TableHead>
                  <TableHead className="px-6 py-3">Away Team</TableHead>
                  <TableHead className="px-6 py-3">Score</TableHead>
                  <TableHead className="px-6 py-3">Odds</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {matches.map((match) => (
                  <TableRow key={match.id}>
                    {/* <TableCell className="px-6 py-4">{match.id}</TableCell> */}
                    <TableCell className="px-6 py-4">{new Date(match.utcDate).toLocaleString()}</TableCell>
                    <TableCell className="px-6 py-4">{match.status}</TableCell>
                    <TableCell className="px-6 py-4">{match.matchday}</TableCell>
                    
                    <TableCell className="px-6 py-4 flex items-center space-x-2">
                      <Image
                        src={match.awayTeam.crest}
                        alt={`${match.awayTeam.name} crest`}
                        width={24}
                        height={24}
                        className="rounded-full object-contain"
                        onError={(e) => {
                          const target = e.target as HTMLImageElement;
                          target.src = '/placeholder.svg';
                        }}
                      />
                      <span>{match.awayTeam.name}</span>
                    </TableCell>
                    <TableCell className="px-6 py-4">
                      {match.score.fullTime.home !== null && match.score.fullTime.away !== null
                        ? `${match.score.fullTime.home} - ${match.score.fullTime.away}`
                        : 'N/A'}
                    </TableCell>
                    <TableCell className="px-6 py-4">
                      Home Win: {match.odds.homeWin} | Draw: {match.odds.draw} | Away Win: {match.odds.awayWin}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
        </>
      )}
    </div>
  );
}

function LeagueSkeleton() {
  return (
    <div className="container mx-auto px-4 py-8">
      {/* League Information Skeleton */}
      <Card className="mb-8">
        <CardHeader className="flex flex-row items-center space-x-4">
          <Skeleton className="w-16 h-16 rounded-full" />
          <div>
            <Skeleton className="h-6 w-40 mb-2" />
            <Skeleton className="h-4 w-24" />
          </div>
        </CardHeader>
        <CardContent>
          <Skeleton className="h-4 w-full mb-2" />
          <Skeleton className="h-4 w-3/4" />
        </CardContent>
      </Card>

      {/* Tabs Skeleton */}
      <div className="mb-6 flex space-x-4">
        <Skeleton className="h-10 w-24 rounded" />
        <Skeleton className="h-10 w-24 rounded" />
        <Skeleton className="h-10 w-24 rounded" />
        <Skeleton className="h-10 w-24 rounded" /> {/* Matches Tab */}
      </div>

      {/* Content Skeleton */}
      <Skeleton className="h-8 w-40 mb-4" />
      {/* Depending on which tab is active, render different skeletons */}
      {/* For simplicity, here's a generic content skeleton */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {[...Array(6)].map((_, index) => (
          <Card key={index}>
            <CardHeader className="flex flex-row items-center space-x-4">
              <Skeleton className="w-12 h-12 rounded-full" />
              <Skeleton className="h-6 w-32" />
            </CardHeader>
            <CardContent>
              <Skeleton className="h-4 w-full mb-2" />
              <Skeleton className="h-4 w-3/4 mb-2" />
              <Skeleton className="h-4 w-1/2" />
            </CardContent>
          </Card>
        ))}
      </div>

      {/* Matches Skeleton */}
      <Skeleton className="h-8 w-40 mb-4 mt-8" />
      <div className="overflow-x-auto">
        <Skeleton className="h-12 w-full mb-2" /> {/* Table Header */}
        {[...Array(5)].map((_, index) => (
          <div key={index} className="flex space-x-4 mb-2">
            <Skeleton className="h-6 w-12" />
            <Skeleton className="h-6 w-24" />
            <Skeleton className="h-6 w-24" />
            <Skeleton className="h-6 w-24" />
            <Skeleton className="h-6 w-24" />
            <Skeleton className="h-6 w-24" />
            <Skeleton className="h-6 w-24" />
          </div>
        ))}
      </div>
    </div>
  )
}
 <Link
                        href={`/players/?query=${scorer.player.name}`}
                        className="text-blue-500 hover:underline"
                      >
                        {scorer.player.name}
                      </Link>
I want this to work in league/page.tsx