"use client";

import { Box, Grid, Text, Flex, Image, HStack, VStack } from "@chakra-ui/react";
import { useTranslations } from "next-intl";
import { useColorModeValue } from "@/components/ui/color-mode";
import {
  StaggerContainer,
  StaggerItem,
  ScrollSlideUp,
} from "@/components/motion";
import { Skeleton } from "@/components/ui/feedback/skeleton";
import MatchCard from "./match-card";
import type {
  LeagueWithMatchesDto,
  MatchResponseDto,
} from "@/lib/api/matches/types";

// ========================
// Match Card Skeleton — realistic loading placeholder
// ========================

function MatchCardSkeleton() {
  const bg = useColorModeValue("white", "gray.800");
  const border = useColorModeValue("gray.100", "gray.700");

  return (
    <Box
      bg={bg}
      borderWidth="1px"
      borderColor={border}
      borderRadius="xl"
      p={4}
      className="animate-shimmer"
    >
      {/* Status + Date */}
      <Flex justify="space-between" align="center" mb={3}>
        <Skeleton borderRadius="full" height="20px" width="60px" />
        <Skeleton borderRadius="md" height="14px" width="80px" />
      </Flex>

      {/* Teams */}
      <HStack gap={3} justify="space-between">
        {/* Home */}
        <VStack gap={1.5} flex={1} align="center">
          <Skeleton boxSize="40px" borderRadius="full" />
          <Skeleton height="14px" width="70px" />
        </VStack>

        {/* VS / Score */}
        <Skeleton height="24px" width="30px" borderRadius="md" />

        {/* Away */}
        <VStack gap={1.5} flex={1} align="center">
          <Skeleton boxSize="40px" borderRadius="full" />
          <Skeleton height="14px" width="70px" />
        </VStack>
      </HStack>

      {/* League */}
      <Flex
        mt={3}
        pt={2}
        borderTopWidth="1px"
        borderColor={border}
        justify="center"
      >
        <Skeleton height="12px" width="120px" />
      </Flex>
    </Box>
  );
}

/** Skeleton grid for loading state */
function MatchListSkeleton() {
  return (
    <Box>
      {/* Fake league header */}
      <Skeleton height="44px" borderRadius="xl" mb={3} />
      <Grid
        templateColumns={{
          base: "1fr",
          md: "repeat(2, 1fr)",
          lg: "repeat(3, 1fr)",
        }}
        gap={3}
      >
        {Array.from({ length: 6 }).map((_, i) => (
          <MatchCardSkeleton key={i} />
        ))}
      </Grid>
    </Box>
  );
}

interface MatchListProps {
  leagues?: LeagueWithMatchesDto[];
  flatMatches?: MatchResponseDto[];
  isLoading?: boolean;
}

/**
 * MatchList — renders matches grouped by league, or flat if only flatMatches is provided.
 */
export default function MatchList({
  leagues,
  flatMatches,
  isLoading,
}: MatchListProps) {
  const t = useTranslations("matches");

  const leagueHeaderBg = useColorModeValue("gray.50", "gray.900");
  const borderColor = useColorModeValue("gray.200", "gray.700");

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

  // Flat mode — no league grouping
  if (flatMatches) {
    if (flatMatches.length === 0) {
      return (
        <Flex justify="center" align="center" py={16}>
          <Text color="fg.muted" fontSize="md">
            {t("no-matches")}
          </Text>
        </Flex>
      );
    }

    const sortedFlatMatches = [...flatMatches].sort(
      (a, b) => Number(a.mstUtc) - Number(b.mstUtc),
    );

    return (
      <StaggerContainer>
        <Grid
          templateColumns={{
            base: "1fr",
            md: "repeat(2, 1fr)",
            lg: "repeat(3, 1fr)",
          }}
          gap={4}
        >
          {sortedFlatMatches.map((match) => (
            <StaggerItem key={match.id}>
              <MatchCard match={match} />
            </StaggerItem>
          ))}
        </Grid>
      </StaggerContainer>
    );
  }

  // Grouped mode — grouped by league
  if (!leagues || leagues.length === 0) {
    return (
      <Flex justify="center" align="center" py={16}>
        <Text color="fg.muted" fontSize="md">
          {t("no-matches")}
        </Text>
      </Flex>
    );
  }

  // Sort leagues by their earliest match, and sort matches within each league
  const sortedLeagues = [...leagues]
    .map((league) => ({
      ...league,
      matches: [...league.matches].sort(
        (a, b) => Number(a.mstUtc) - Number(b.mstUtc),
      ),
    }))
    .sort((a, b) => {
      const earliestA = Math.min(...a.matches.map((m) => Number(m.mstUtc)));
      const earliestB = Math.min(...b.matches.map((m) => Number(m.mstUtc)));
      return earliestA - earliestB;
    });

  return (
    <StaggerContainer>
      {sortedLeagues.map((league) => (
        <StaggerItem key={league.id}>
          <Box mb={6}>
            {/* League Header */}
            <Flex
              align="center"
              gap={2}
              px={4}
              py={2.5}
              bg={leagueHeaderBg}
              borderRadius="xl"
              borderWidth="1px"
              borderColor={borderColor}
              mb={3}
            >
              {league.country?.flagUrl && (
                <Image
                  src={league.country.flagUrl}
                  alt={league.country.name || ""}
                  boxSize="20px"
                  objectFit="contain"
                />
              )}
              <Text fontSize="sm" fontWeight="bold">
                {league.country?.name && `${league.country.name} • `}
                {league.name}
              </Text>
              <Text fontSize="xs" color="fg.muted" ml="auto">
                {t("match-count", { count: league.matches.length })}
              </Text>
            </Flex>

            {/* Match Grid */}
            <Grid
              templateColumns={{
                base: "1fr",
                md: "repeat(2, 1fr)",
                lg: "repeat(3, 1fr)",
              }}
              gap={3}
            >
              {league.matches.map((match) => (
                <MatchCard key={match.id} match={match} />
              ))}
            </Grid>
          </Box>
        </StaggerItem>
      ))}
    </StaggerContainer>
  );
}
