"use client";
import { useState, useEffect } from "react";

const MatchDays = ({ onSelectMatch }) => {
  const [activeIndex, setActiveIndex] = useState(0);
  const [matchDays, setMatchDays] = useState([]);

  useEffect(() => {
    getMatchDays();
  }, []);

  useEffect(() => {
    console.log("matchDays", matchDays);
    if (matchDays.length > 0) {
      getMatchesByDate(matchDays[0].date);
    }
  }, [matchDays]);

  async function getMatchDays() {
    try {
      const response = await fetch("/api/match?action=getMatchDays");
      if (!response.ok) {
        throw new Error("Network response was not ok");
      }
      const res = await response.json();
      console.log("MatchDays", res.data);
      setMatchDays(res.data);
    } catch (error) {
      console.error("Error fetching match days:", error);
      throw error;
    }
  }

  // 根据日期获取比赛
  async function getMatchesByDate(date) {
    console.log("date", date);
    try {
      const response = await fetch(
        `/api/match?action=getMatchesByDate&date=${date}`
      );

      if (!response.ok) {
        throw new Error("Network response was not ok");
      }
      const res = await response.json();
      console.log("Matches", res.data);
      onSelectMatch(res.data);
    } catch (error) {
      console.error("Error fetching matches by date:", error);
      throw error;
    }
  }

  // 搜索比赛
  const searchMatches = (index, date) => {
    setActiveIndex(index);
    getMatchesByDate(date);
  };

  return (
    <nav className="bg-blue-500 pt-4 pb-2 px-4 max-w-md mx-auto">
      <div className="container text-center text-white overflow-x-auto no-scrollbar whitespace-nowrap">
        <ul className="flex space-x-6">
          {matchDays.map((item, index) => (
            <li key={item.id} className="relative group">
              <a
                onClick={() => searchMatches(index, item.date)}
                className="text-white"
              >
                <span className="block mb-1">{item.title}</span>
                <span className="block text-sm text-white mb-3">
                  {item.date}
                </span>
              </a>
              {/* </Link> */}
              {activeIndex === index && (
                <span className="absolute bottom-0 left-0 right-0 block w-full h-1 bg-red-500"></span>
              )}
            </li>
          ))}
        </ul>
        {/* </div> */}
      </div>
    </nav>
  );
};

export default MatchDays;
