"use client";

import {
  Box,
  Flex,
  Text,
  Heading,
  Badge,
  VStack,
  HStack,
  Image,
  Spinner,
  Button,
  Card,
} from "@chakra-ui/react";
import { useLocale, useTranslations } from "next-intl";
import { useParams, useRouter } from "next/navigation";
import { useSession } from "next-auth/react";
import { useColorModeValue } from "@/components/ui/color-mode";
import { SlideUp, FadeIn } from "@/components/motion";
import { useTeamById, useTeamMatches } from "@/lib/api/leagues/use-hooks";
import {
  LuArrowLeft,
  LuCalendar,
  LuTrophy,
  LuChevronDown,
} from "react-icons/lu";
import type { MatchResponseDto } from "@/lib/api/matches/types";
import { useState, useMemo, useCallback } from "react";
import { LoginModal } from "@/components/auth/login-modal";

// ─────────────────────────────────────────────────
// Utility Functions
// ─────────────────────────────────────────────────

function getMatchTimestamp(match: MatchResponseDto): number {
  const raw =
    typeof match.mstUtc === "string" ? Number(match.mstUtc) : match.mstUtc;
  return Number.isFinite(raw) ? raw : 0;
}

function getMatchStatus(match: MatchResponseDto): string {
  return String(match.status || match.state || "").toUpperCase();
}

function isMatchFinished(match: MatchResponseDto): boolean {
  const status = getMatchStatus(match);
  return (
    status === "FT" ||
    status === "FINISHED" ||
    status === "POSTGAME" ||
    status === "POST_GAME"
  );
}

function isMatchLive(match: MatchResponseDto): boolean {
  const status = getMatchStatus(match);
  return (
    status === "LIVE" || status === "INPROGRESS" || status === "IN_PROGRESS"
  );
}

function getTeamSideName(
  team: MatchResponseDto["homeTeam"] | MatchResponseDto["awayTeam"],
  fallback?: unknown,
): string {
  return String(team?.name || fallback || "");
}

function getTeamSideLogo(
  team: MatchResponseDto["homeTeam"] | MatchResponseDto["awayTeam"],
  fallback?: unknown,
): string {
  return String(team?.logo || fallback || "");
}

function getLeagueLabel(match: MatchResponseDto): string {
  return String(match.leagueName || match.league?.name || "");
}

function getSeasonFromTimestamp(timestampMs: number): string {
  const date = new Date(timestampMs);
  const year = date.getFullYear();
  const month = date.getMonth() + 1; // 1-indexed

  if (month >= 8) {
    return `${year}-${year + 1}`;
  }
  return `${year - 1}-${year}`;
}

const SEASONS = (() => {
  const currentYear = new Date().getFullYear();
  const currentMonth = new Date().getMonth() + 1;
  const startYear = currentMonth >= 8 ? currentYear : currentYear - 1;
  return Array.from(
    { length: 5 },
    (_, i) => `${startYear - i}-${startYear - i + 1}`,
  );
})();

// ─────────────────────────────────────────────────
// Main Component
// ─────────────────────────────────────────────────

export default function TeamDetailContent() {
  const t = useTranslations();
  const params = useParams();
  const router = useRouter();
  const { data: session } = useSession();
  const [loginModalOpen, setLoginModalOpen] = useState(false);

  const teamId = params.id as string;
  const [currentPage, setCurrentPage] = useState(1);
  const [activeSeason, setActiveSeason] = useState<string>(SEASONS[0]);

  const { data: teamData, isLoading: teamLoading } = useTeamById(teamId);
  const {
    data: matchesResponse,
    isLoading: matchesLoading,
    isFetching: matchesFetching,
  } = useTeamMatches(teamId, {
    page: currentPage,
    limit: 20,
    season: activeSeason,
  });

  const cardBg = useColorModeValue("white", "gray.800");
  const borderColor = useColorModeValue("gray.100", "gray.700");
  const seasonActiveBg = useColorModeValue("primary.500", "primary.400");
  const seasonInactiveBg = useColorModeValue("gray.100", "gray.700");

  // Backend ResponseInterceptor wraps all responses in { success, status, message, data }
  const teamWrapper = teamData as Record<string, unknown> | undefined;
  const team = teamWrapper?.data as Record<string, unknown> | undefined;

  // matchesResponse = { success, status, message, data: { data: [...], total, page, limit, totalPages } }
  const paginationWrapper = matchesResponse as
    | Record<string, unknown>
    | undefined;
  const paginationData = paginationWrapper?.data as
    | Record<string, unknown>
    | undefined;
  const matches: MatchResponseDto[] = (
    Array.isArray(paginationData?.data)
      ? paginationData.data
      : paginationData?.data
        ? []
        : []
  ) as MatchResponseDto[];
  const totalPages = (paginationData?.totalPages as number) ?? 1;
  const totalMatches = (paginationData?.total as number) ?? 0;

  // Separate past and upcoming matches
  const pastMatches = useMemo(
    () => matches.filter((m) => isMatchFinished(m)),
    [matches],
  );
  const upcomingMatches = useMemo(
    () => matches.filter((m) => !isMatchFinished(m)),
    [matches],
  );

  // Pagination handlers
  const handleNextPage = useCallback(() => {
    if (currentPage < totalPages) {
      setCurrentPage((p) => p + 1);
    }
  }, [currentPage, totalPages]);

  const handlePrevPage = useCallback(() => {
    if (currentPage > 1) {
      setCurrentPage((p) => p - 1);
    }
  }, [currentPage]);

  const getStatusBadge = (match: MatchResponseDto) => {
    if (isMatchLive(match))
      return (
        <Badge colorPalette="red" variant="subtle" fontSize="xs">
          {t("matches.live")}
        </Badge>
      );
    if (isMatchFinished(match))
      return (
        <Badge colorPalette="gray" variant="subtle" fontSize="xs">
          {t("matches.finished")}
        </Badge>
      );
    return (
      <Badge colorPalette="green" variant="subtle" fontSize="xs">
        {t("teams.upcoming")}
      </Badge>
    );
  };

  if (teamLoading) {
    return (
      <Flex justify="center" align="center" py={20}>
        <Spinner size="lg" color="primary.500" />
      </Flex>
    );
  }

  if (!team) {
    return (
      <Flex justify="center" py={20} direction="column" align="center" gap={4}>
        <Text color="fg.muted" fontSize="lg">
          {t("teams.not-found")}
        </Text>
        <Button variant="outline" onClick={() => router.back()}>
          <LuArrowLeft /> {t("common.back")}
        </Button>
      </Flex>
    );
  }

  return (
    <SlideUp>
      <Box>
        {/* Back Button */}
        <Button
          variant="ghost"
          size="sm"
          mb={4}
          onClick={() => router.back()}
          gap={1.5}
        >
          <LuArrowLeft />
          Geri
        </Button>

        {/* Team Header */}
        <Card.Root
          bg={cardBg}
          borderColor={borderColor}
          borderRadius="xl"
          mb={6}
        >
          <Card.Body>
            <HStack gap={6} justify="center" align="center">
              {(team as Record<string, unknown>).logo ? (
                <Image
                  src={String((team as Record<string, unknown>).logo)}
                  alt={String((team as Record<string, unknown>).name)}
                  boxSize="80px"
                  objectFit="contain"
                />
              ) : (
                <Flex
                  boxSize="80px"
                  bg="primary.subtle"
                  borderRadius="xl"
                  align="center"
                  justify="center"
                >
                  <Text fontSize="3xl" fontWeight="bold" color="primary.fg">
                    {String(
                      (team as Record<string, unknown>).name || "T",
                    ).charAt(0)}
                  </Text>
                </Flex>
              )}
              <VStack gap={1} align="start">
                <Heading as="h1" size="xl">
                  {String((team as Record<string, unknown>).name)}
                </Heading>
                {Boolean((team as Record<string, unknown>).country) && (
                  <Text fontSize="md" color="fg.muted">
                    🌍 {String((team as Record<string, unknown>).country)}
                  </Text>
                )}
                <HStack gap={4} mt={1}>
                  <Badge colorPalette="blue" variant="subtle">
                    <LuTrophy style={{ width: 12, height: 12 }} />
                    {totalMatches} {t("teams.matches-count")}
                  </Badge>
                  <Badge colorPalette="green" variant="subtle">
                    <LuCalendar style={{ width: 12, height: 12 }} />
                    {upcomingMatches.length} {t("teams.upcoming")}
                  </Badge>
                </HStack>
              </VStack>
            </HStack>
          </Card.Body>
        </Card.Root>

        {/* Upcoming Matches */}
        {upcomingMatches.length > 0 && (
          <FadeIn>
            <Box mb={6}>
              <Heading as="h2" size="lg" mb={4}>
                📅 {t("teams.upcoming-matches")}
              </Heading>
              <VStack gap={2} align="stretch">
                {upcomingMatches.map((match: MatchResponseDto) => (
                  <MatchRow
                    key={match.id}
                    match={match}
                    cardBg={cardBg}
                    borderColor={borderColor}
                    statusBadge={getStatusBadge(match)}
                    onClick={() =>
                      session
                        ? router.push(`/matches/${match.id}`)
                        : setLoginModalOpen(true)
                    }
                  />
                ))}
              </VStack>
            </Box>
          </FadeIn>
        )}

        {/* Past Matches — Season Grouped */}
        <FadeIn>
          <Box>
            <Flex
              align="center"
              justify="space-between"
              mb={4}
              flexWrap="wrap"
              gap={2}
            >
              <Heading as="h2" size="lg">
                📊 {t("teams.past-matches")}
              </Heading>
              {/* Pagination Info */}
              <Text fontSize="xs" color="fg.muted">
                {t("teams.page-info", { page: currentPage, totalPages, total: totalMatches })}
              </Text>
            </Flex>

            {/* Season Tabs */}
            {SEASONS.length > 0 && (
              <HStack gap={2} mb={4} flexWrap="wrap">
                {SEASONS.map((season) => {
                  const isActive = season === activeSeason;
                  return (
                    <Button
                      key={season}
                      size="sm"
                      variant={isActive ? "solid" : "outline"}
                      bg={isActive ? seasonActiveBg : seasonInactiveBg}
                      color={isActive ? "white" : undefined}
                      borderRadius="full"
                      fontWeight={isActive ? "700" : "500"}
                      fontSize="xs"
                      px={4}
                      onClick={() => {
                        setActiveSeason(season);
                        setCurrentPage(1);
                      }}
                      _hover={{
                        transform: "translateY(-1px)",
                        shadow: "sm",
                      }}
                      transition="all 0.2s"
                    >
                      🏆 {season}
                    </Button>
                  );
                })}
              </HStack>
            )}

            {matchesLoading || matchesFetching ? (
              <Flex justify="center" py={8}>
                <Spinner size="md" color="primary.500" />
              </Flex>
            ) : pastMatches.length === 0 ? (
              <Text color="fg.muted" textAlign="center" py={8}>
                {t("teams.no-past-matches-season")}
              </Text>
            ) : (
              <VStack gap={2} align="stretch">
                {pastMatches.map((match: MatchResponseDto) => (
                  <MatchRow
                    key={match.id}
                    match={match}
                    cardBg={cardBg}
                    borderColor={borderColor}
                    statusBadge={getStatusBadge(match)}
                    onClick={() =>
                      session
                        ? router.push(`/matches/${match.id}`)
                        : setLoginModalOpen(true)
                    }
                  />
                ))}
              </VStack>
            )}

            {/* Pagination Controls */}
            {totalPages > 1 && (
              <Flex justify="center" gap={3} mt={6} align="center">
                <Button
                  size="sm"
                  variant="outline"
                  onClick={handlePrevPage}
                  disabled={currentPage <= 1}
                  borderRadius="full"
                >
                  ← {t("common.previous")}
                </Button>
                <HStack gap={1}>
                  {Array.from({ length: Math.min(totalPages, 7) }, (_, i) => {
                    // Show pages around current page
                    let pageNum: number;
                    if (totalPages <= 7) {
                      pageNum = i + 1;
                    } else if (currentPage <= 4) {
                      pageNum = i + 1;
                    } else if (currentPage >= totalPages - 3) {
                      pageNum = totalPages - 6 + i;
                    } else {
                      pageNum = currentPage - 3 + i;
                    }

                    return (
                      <Button
                        key={pageNum}
                        size="sm"
                        variant={pageNum === currentPage ? "solid" : "ghost"}
                        bg={
                          pageNum === currentPage ? seasonActiveBg : undefined
                        }
                        color={pageNum === currentPage ? "white" : undefined}
                        borderRadius="full"
                        minW="36px"
                        onClick={() => {
                          setCurrentPage(pageNum);
                        }}
                      >
                        {pageNum}
                      </Button>
                    );
                  })}
                </HStack>
                <Button
                  size="sm"
                  variant="outline"
                  onClick={handleNextPage}
                  disabled={currentPage >= totalPages}
                  borderRadius="full"
                >
                  {t("common.next")} →
                </Button>
              </Flex>
            )}
          </Box>
        </FadeIn>

        {/* Login Modal — shown when unauthenticated user clicks a match */}
        <LoginModal
          open={loginModalOpen}
          onOpenChange={setLoginModalOpen}
          initialMode="login"
        />
      </Box>
    </SlideUp>
  );
}

// ─────────────────────────────────────────────────
// Match Row Component
// ─────────────────────────────────────────────────

interface MatchRowProps {
  match: MatchResponseDto;
  cardBg: string;
  borderColor: string;
  statusBadge: React.ReactNode;
  onClick: () => void;
}

function MatchRow({
  match,
  cardBg,
  borderColor,
  statusBadge,
  onClick,
}: MatchRowProps) {
  const locale = useLocale();
  const hoverBg = useColorModeValue("gray.50", "gray.700");
  const matchTimestamp = getMatchTimestamp(match);
  const homeTeamName = getTeamSideName(match.homeTeam, match.homeTeamName);
  const awayTeamName = getTeamSideName(match.awayTeam, match.awayTeamName);
  const homeTeamLogo = getTeamSideLogo(match.homeTeam, match.homeTeamLogo);
  const awayTeamLogo = getTeamSideLogo(match.awayTeam, match.awayTeamLogo);
  const leagueLabel = getLeagueLabel(match);
  const hasScore = isMatchFinished(match) || isMatchLive(match);

  return (
    <Card.Root
      bg={cardBg}
      borderColor={borderColor}
      borderRadius="lg"
      cursor="pointer"
      transition="all 0.2s"
      _hover={{ bg: hoverBg, transform: "translateY(-1px)", shadow: "sm" }}
      onClick={onClick}
    >
      <Card.Body py={3} px={4}>
        <Flex justify="space-between" align="center">
          <HStack gap={3} flex={1}>
            {/* Home Team */}
            <HStack gap={2} flex={1} justify="flex-end">
              <Text fontSize="sm" fontWeight="600" textAlign="right" truncate>
                {homeTeamName}
              </Text>
              {homeTeamLogo ? (
                <Image
                  src={homeTeamLogo}
                  alt=""
                  boxSize="24px"
                  objectFit="contain"
                  flexShrink={0}
                />
              ) : (
                <Flex
                  boxSize="24px"
                  bg="primary.subtle"
                  borderRadius="full"
                  align="center"
                  justify="center"
                  flexShrink={0}
                >
                  <Text fontSize="xs" fontWeight="bold">
                    {homeTeamName?.charAt(0)}
                  </Text>
                </Flex>
              )}
            </HStack>

            {/* Score / VS */}
            <VStack gap={0} flexShrink={0} minW="60px">
              {hasScore &&
              match.scoreHome !== undefined &&
              match.scoreHome !== null ? (
                <Text fontSize="md" fontWeight="900">
                  {match.scoreHome} - {match.scoreAway}
                </Text>
              ) : (
                <Text fontSize="sm" color="fg.muted" fontWeight="600">
                  vs
                </Text>
              )}
              <Text fontSize="2xs" color="fg.muted">
                {matchTimestamp
                  ? new Date(matchTimestamp).toLocaleDateString(locale, {
                      day: "2-digit",
                      month: "short",
                    })
                  : "-"}
              </Text>
            </VStack>

            {/* Away Team */}
            <HStack gap={2} flex={1}>
              {awayTeamLogo ? (
                <Image
                  src={awayTeamLogo}
                  alt=""
                  boxSize="24px"
                  objectFit="contain"
                  flexShrink={0}
                />
              ) : (
                <Flex
                  boxSize="24px"
                  bg="primary.subtle"
                  borderRadius="full"
                  align="center"
                  justify="center"
                  flexShrink={0}
                >
                  <Text fontSize="xs" fontWeight="bold">
                    {awayTeamName?.charAt(0)}
                  </Text>
                </Flex>
              )}
              <Text fontSize="sm" fontWeight="600" truncate>
                {awayTeamName}
              </Text>
            </HStack>
          </HStack>

          {/* Status + League */}
          <HStack gap={2} flexShrink={0} ml={3}>
            {leagueLabel && (
              <Text
                fontSize="2xs"
                color="fg.muted"
                display={{ base: "none", md: "block" }}
              >
                {leagueLabel}
              </Text>
            )}
            {statusBadge}
          </HStack>
        </Flex>
      </Card.Body>
    </Card.Root>
  );
}
