Request URL:
http://localhost:3000/leagues/EC
Request Method:
GET
Status Code:
404 Not Found
Remote Address:
[::1]:3000
Referrer Policy:
strict-origin-when-cross-origin
cache-control:
no-store, must-revalidate
connection:
keep-alive
content-encoding:
gzip
content-type:
text/html; charset=utf-8
date:
Wed, 25 Sep 2024 09:05:28 GMT
keep-alive:
timeout=5
transfer-encoding:
chunked
vary:
RSC, Next-Router-State-Tree, Next-Router-Prefetch, Accept-Encoding
x-powered-by:
Next.js
accept:
text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
accept-encoding:
gzip, deflate, br, zstd
accept-language:
en-US,en;q=0.9,en-IN;q=0.8
cache-control:
max-age=0
connection:
keep-alive
dnt:
1
host:
localhost:3000
referer:
http://localhost:3000/
sec-ch-ua:
"Chromium";v="128", "Not;A=Brand";v="24", "Microsoft Edge";v="128"
sec-ch-ua-mobile:
?0
sec-ch-ua-platform:
"Windows"
sec-fetch-dest:
document
sec-fetch-mode:
navigate
sec-fetch-site:
same-origin
sec-fetch-user:
?1
upgrade-insecure-requests:
1
user-agent:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 Edg/128.0.0.0
// pages/leagues/[code].tsx

import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Table } from "@/components/ui/table";
import axios from 'axios';

interface LeagueInfo {
  id: number;
  name: string;
  area: {
    id: number;
    name: string;
    code: string;
    flag: string;
  };
  code: string;
  type: string;
  emblem: string;
  currentSeason: {
    id: number;
    startDate: string;
    endDate: string;
    currentMatchday: number;
    winner: any;
    stages: string[];
  };
  lastUpdated: string;
}

interface Team {
  id: number;
  name: string;
  shortName: string;
  tla: string;
  crest: string;
  venue: string;
  website: string;
  founded: number;
  clubColors: string;
}

interface LeagueData {
  league: LeagueInfo;
  teams: Team[];
}

export default function LeagueDetail() {
  const router = useRouter();
  const { code } = router.query;
  const [leagueData, setLeagueData] = useState<LeagueData | null>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);

  // Retrieve backend URL from environment variables
  const backendUrl = process.env.NEXT_PUBLIC_BACKEND_URL || 'http://localhost:5000';

  useEffect(() => {
    if (!code) return;

    // Ensure `code` is a string
    const leagueCode = Array.isArray(code) ? code[0] : code;

    const fetchLeagueDetails = async () => {
      try {
        const response = await axios.get<LeagueData>(`${backendUrl}/api/league/${leagueCode}`);
        setLeagueData(response.data);
      } catch (err: any) {
        console.error('Error fetching league details:', err);
        setError(err.response?.data?.message || 'Failed to load league details.');
      } finally {
        setLoading(false);
      }
    };

    fetchLeagueDetails();
  }, [code, backendUrl]);

  if (loading) {
    return <p className="text-center text-gray-500">Loading league details...</p>;
  }

  if (error) {
    return <p className="text-center text-red-500">Error: {error}</p>;
  }

  if (!leagueData) {
    return <p className="text-center text-gray-500">No league data found.</p>;
  }

  const { league, teams } = leagueData;

  return (
    <div className="container mx-auto p-4 space-y-8">
      {/* League Information */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center space-x-4">
            <img src={league.emblem} alt={`${league.name} Emblem`} className="w-12 h-12" />
            <span className="text-2xl font-bold">{league.name}</span>
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <p><strong>Area:</strong> {league.area.name}</p>
              <p><strong>Code:</strong> {league.code}</p>
              <p><strong>Type:</strong> {league.type}</p>
            </div>
            <div>
              <p><strong>Current Matchday:</strong> {league.currentSeason.currentMatchday}</p>
              <p><strong>Season Start:</strong> {new Date(league.currentSeason.startDate).toLocaleDateString()}</p>
              <p><strong>Season End:</strong> {new Date(league.currentSeason.endDate).toLocaleDateString()}</p>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Teams Table */}
      <Card>
        <CardHeader>
          <CardTitle>Teams</CardTitle>
        </CardHeader>
        <CardContent>
          <Table className="w-full">
            <thead>
              <tr className="bg-gray-100 dark:bg-gray-700">
                <th className="px-4 py-2 border">ID</th>
                <th className="px-4 py-2 border">Name</th>
                <th className="px-4 py-2 border">Short Name</th>
                <th className="px-4 py-2 border">TLA</th>
                <th className="px-4 py-2 border">Venue</th>
                <th className="px-4 py-2 border">Founded</th>
                <th className="px-4 py-2 border">Club Colors</th>
              </tr>
            </thead>
            <tbody>
              {teams.map((team) => (
                <tr key={team.id} className="hover:bg-gray-50 dark:hover:bg-gray-800">
                  <td className="px-4 py-2 border text-center">{team.id}</td>
                  <td className="px-4 py-2 border">{team.name}</td>
                  <td className="px-4 py-2 border">{team.shortName}</td>
                  <td className="px-4 py-2 border">{team.tla}</td>
                  <td className="px-4 py-2 border">{team.venue}</td>
                  <td className="px-4 py-2 border text-center">{team.founded}</td>
                  <td className="px-4 py-2 border">{team.clubColors}</td>
                </tr>
              ))}
            </tbody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
}

// components/LeagueSelector.tsx

'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import axios from 'axios';
import {
  NavigationMenu,
  NavigationMenuList,
  NavigationMenuItem,
  NavigationMenuLink,
  NavigationMenuTrigger,
  NavigationMenuContent,
  NavigationMenuViewport,
  navigationMenuTriggerStyle,
} from "@/components/ui/navigation-menu";

interface League {
  id: number;
  name: string;
  code: string;
  emblem: string;
  area: {
    id: number;
    name: string;
    code: string;
    flag: string;
  };
}

interface LeaguesResponse {
  count: number;
  leagues: League[];
}

export default function LeagueSelector() {
  const [leagues, setLeagues] = useState<League[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);

  // Retrieve backend URL from environment variables
  const backendUrl = process.env.NEXT_PUBLIC_BACKEND_URL || 'http://localhost:5000';

  useEffect(() => {
    const fetchLeagues = async () => {
      try {
        const response = await axios.get<LeaguesResponse>(`${backendUrl}/api/leagues`);
        console.log('Leagues data:', response.data); // Debugging line
        if (response.data && Array.isArray(response.data.leagues)) {
          setLeagues(response.data.leagues);
        } else {
          throw new Error('Invalid data format received from API.');
        }
      } catch (err: any) {
        console.error('Error fetching leagues:', err);
        setError(err.response?.data?.message || 'Failed to load leagues.');
      } finally {
        setLoading(false);
      }
    };

    fetchLeagues();
  }, [backendUrl]);

  if (loading) {
    return <p className="text-center text-gray-500">Loading leagues...</p>;
  }

  if (error) {
    return <p className="text-center text-red-500">Error: {error}</p>;
  }

  if (!Array.isArray(leagues) || leagues.length === 0) {
    return <p className="text-center text-gray-500">No leagues found.</p>;
  }

  return (
    <div className="w-full max-w-4xl mx-auto p-4">
      <NavigationMenu>
        <NavigationMenuList>
          {leagues.map((league) => (
            <NavigationMenuItem key={league.id}>
              <NavigationMenuTrigger className={navigationMenuTriggerStyle()}>
                <div className="flex items-center space-x-2">
                  <img src={league.emblem} alt={`${league.name} Emblem`} className="w-6 h-6" />
                  <span>{league.name}</span>
                </div>
              </NavigationMenuTrigger>
              <NavigationMenuContent>
                <div className="grid gap-4 p-4 bg-white dark:bg-gray-800">
                  <Link href={`/leagues/${league.code}`} legacyBehavior passHref>
                    <NavigationMenuLink className="block p-2 rounded-md hover:bg-gray-100 dark:hover:bg-gray-700">
                      View Details
                    </NavigationMenuLink>
                  </Link>
                  {/* Add more links or actions here if needed */}
                </div>
              </NavigationMenuContent>
            </NavigationMenuItem>
          ))}
        </NavigationMenuList>
        <NavigationMenuViewport />
      </NavigationMenu>
    </div>
  );
}
Find out the error and correct it