"use client";

import { Box, Flex, Heading } from "@chakra-ui/react";
import { useEffect } from "react";
import { useTranslations } from "next-intl";
import { SlideUp } from "@/components/motion";
import { SportFilter, LeagueSidebar, MatchList } from "@/components/matches";
import { useQueryMatches, useActiveLeagues } from "@/lib/api/matches/use-hooks";
import { useMatchStore } from "@/lib/stores/match-store";

export default function MatchesContent() {
  const t = useTranslations("matches");

  const sport = useMatchStore((s) => s.sport);
  const leagueFilter = useMatchStore((s) => s.leagueFilter);
  const setSport = useMatchStore((s) => s.setSport);
  const setLeague = useMatchStore((s) => s.setLeague);

  // Fetch active leagues for sidebar
  const { data: leaguesData, isLoading: leaguesLoading } =
    useActiveLeagues(sport);
  const leagues = leaguesData?.data ?? [];

  // Query matches grouped by league
  const queryMatches = useQueryMatches();

  // Trigger query on sport/league change
  const { data: matchesData, isPending: matchesLoading } = (() => {
    // We use the queryMatches mutation for initial data
    // but for the UI we want a reactive approach.
    // Let's use the standard list with league filter
    return {
      data: queryMatches.data,
      isPending: queryMatches.isPending,
    };
  })();

  // Auto-trigger query when sport or league changes
  const handleSportChange = (newSport: typeof sport) => {
    setSport(newSport);
    queryMatches.mutate({
      sport: newSport,
      leagueId: undefined,
      limit: 100,
    });
  };

  const handleLeagueChange = (leagueId: string | null) => {
    setLeague(leagueId);
    queryMatches.mutate({
      sport,
      leagueId: leagueId || undefined,
      limit: 100,
    });
  };

  // Initial load
  useEffect(() => {
    if (!queryMatches.data && !queryMatches.isPending) {
      queryMatches.mutate({
        sport,
        leagueId: leagueFilter || undefined,
        limit: 100,
      });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const matchLeagues = matchesData?.data ?? [];

  return (
    <SlideUp>
      <Box>
        {/* Page Header */}
        <Flex
          justify="space-between"
          align="center"
          mb={6}
          flexWrap="wrap"
          gap={3}
        >
          <Heading as="h1" size="xl" fontWeight="bold">
            {t("title")}
          </Heading>
          <SportFilter value={sport} onChange={handleSportChange} />
        </Flex>

        {/* Main Content */}
        <Flex
          gap={6}
          align="flex-start"
          direction={{ base: "column", lg: "row" }}
        >
          {/* League Sidebar (Desktop only) */}
          <Box
            display={{ base: "none", lg: "block" }}
            w="260px"
            flexShrink={0}
            position="sticky"
            top="80px"
          >
            <LeagueSidebar
              leagues={leagues}
              selectedLeagueId={leagueFilter}
              onSelect={handleLeagueChange}
              isLoading={leaguesLoading}
            />
          </Box>

          {/* Match List */}
          <Box flex={1} minW={0}>
            <MatchList
              leagues={matchLeagues}
              isLoading={queryMatches.isPending}
            />
          </Box>
        </Flex>
      </Box>
    </SlideUp>
  );
}
