"use client";

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

type QuickFilter = "all" | "today" | "live" | "next_1_hour";

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);

  const [quickFilter, setQuickFilter] = useState<QuickFilter>("all");
  const [dateFilter, setDateFilter] = useState<string>("");

  // 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 } = (() => {
    return {
      data: queryMatches.data,
      isPending: queryMatches.isPending,
    };
  })();

  const triggerQuery = (
    currentSport: typeof sport,
    currentLeague: string | null,
    currentFilter: QuickFilter,
    currentDate?: string,
  ) => {
    const payload: any = {
      sport: currentSport,
      leagueId: currentLeague || undefined,
      limit: 100,
    };

    if (currentDate) {
      payload.date = currentDate;
    } else if (currentFilter === "today") {
      // YYYY-MM-DD for today
      payload.date = new Date().toISOString().split("T")[0];
    } else if (currentFilter === "live") {
      payload.status = "LIVE";
    } else if (currentFilter === "next_1_hour") {
      payload.dateRange = {
        from: new Date().toISOString(),
        to: new Date(Date.now() + 60 * 60 * 1000).toISOString(),
      };
    }

    queryMatches.mutate(payload);
  };

  // Auto-trigger query when sport or league changes
  const handleSportChange = (newSport: typeof sport) => {
    setSport(newSport);
    setLeague(null);
    triggerQuery(newSport, null, quickFilter, dateFilter);
  };

  const handleLeagueChange = (leagueId: string | null) => {
    setLeague(leagueId);
    triggerQuery(sport, leagueId, quickFilter, dateFilter);
  };

  const handleQuickFilterChange = (filter: QuickFilter) => {
    setDateFilter(""); // Clear specific date
    setQuickFilter(filter);
    triggerQuery(sport, leagueFilter, filter, undefined);
  };

  // Initial load
  useEffect(() => {
    if (!queryMatches.data && !queryMatches.isPending) {
      triggerQuery(sport, leagueFilter, quickFilter, dateFilter);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

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

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

        {/* Quick Filters */}
        <Flex
          mb={6}
          overflowX="auto"
          pb={2}
          css={{ "&::-webkit-scrollbar": { display: "none" } }}
          gap={4}
          align="center"
        >
          <Group attached>
            <Button
              size="sm"
              onClick={() => handleQuickFilterChange("all")}
              colorPalette={quickFilter === "all" ? "primary" : "gray"}
              variant={quickFilter === "all" ? "solid" : "outline"}
            >
              {t("all-matches")}
            </Button>
            <Button
              size="sm"
              onClick={() => handleQuickFilterChange("today")}
              colorPalette={quickFilter === "today" ? "primary" : "gray"}
              variant={quickFilter === "today" ? "solid" : "outline"}
            >
              {t("today-matches")}
            </Button>
            <Button
              size="sm"
              onClick={() => handleQuickFilterChange("live")}
              colorPalette={quickFilter === "live" ? "primary" : "gray"}
              variant={quickFilter === "live" ? "solid" : "outline"}
            >
              {t("live")}
            </Button>
            <Button
              size="sm"
              onClick={() => handleQuickFilterChange("next_1_hour")}
              colorPalette={quickFilter === "next_1_hour" ? "primary" : "gray"}
              variant={quickFilter === "next_1_hour" ? "solid" : "outline"}
            >
              {t("next-1-hour")}
            </Button>
          </Group>

          <Input
            type="date"
            size="sm"
            w="auto"
            minW="150px"
            flexShrink={0}
            borderRadius="md"
            value={dateFilter}
            onChange={(e) => {
              const dateVal = e.target.value;
              setDateFilter(dateVal);
              if (dateVal) {
                setQuickFilter("all"); // Reset quick filter highlight
                triggerQuery(sport, leagueFilter, "all", dateVal);
              } else {
                handleQuickFilterChange("all");
              }
            }}
          />
        </Flex>

        {/* Mobile League Filter Bar (visible on small screens only) */}
        <Box display={{ base: "block", lg: "none" }} mb={4}>
          <LeagueFilterBar
            leagues={leagues}
            selectedLeagueId={leagueFilter}
            onSelect={handleLeagueChange}
            isLoading={leaguesLoading}
          />
        </Box>

        {/* Main Content */}
        <Flex
          gap={6}
          align={{ base: "stretch", lg: "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>
  );
}
