"use client";

import {
  Box,
  Flex,
  Heading,
  Text,
  Badge,
  VStack,
  HStack,
  Card,
  SimpleGrid,
  Spinner,
  Button,
} from "@chakra-ui/react";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { useColorModeValue } from "@/components/ui/color-mode";
import { SlideUp, StaggerContainer, StaggerItem } from "@/components/motion";
import type { SportType } from "@/lib/api/matches/types";
import {
  useUpcomingPredictions,
  useValueBets,
  usePredictionHistory,
} from "@/lib/api/predictions/use-hooks";
import type {
  MatchPredictionDto,
  ValueBetDto,
  PredictionHistoryResponseDto,
} from "@/lib/api/predictions/types";
import { useState } from "react";

function getPredictionSport(prediction: MatchPredictionDto): SportType {
  const explicitSport = prediction.match_info?.sport;
  if (explicitSport === "basketball" || explicitSport === "football") {
    return explicitSport;
  }

  if (
    prediction.model_version?.toLowerCase().includes("basketball") ||
    Object.keys(prediction.market_board || {}).some((market) =>
      ["ML", "TOTAL", "SPREAD"].includes(market),
    )
  ) {
    return "basketball";
  }

  return "football";
}

type TabType = "upcoming" | "value-bets" | "history";

export default function PredictionsContent() {
  const t = useTranslations("predictions");
  const tMatches = useTranslations("matches");
  const router = useRouter();
  const [activeTab, setActiveTab] = useState<TabType>("upcoming");

  const cardBg = useColorModeValue("white", "gray.800");
  const borderColor = useColorModeValue("gray.100", "gray.700");

  const { data: upcomingData, isLoading: upcomingLoading } =
    useUpcomingPredictions();
  const { data: valueBetsData, isLoading: valueBetsLoading } = useValueBets();
  const { data: historyData, isLoading: historyLoading } =
    usePredictionHistory();

  const upcomingPredictions: MatchPredictionDto[] =
    upcomingData?.data?.matches ?? [];
  const valueBets: ValueBetDto[] = valueBetsData?.data ?? [];
  const historyResponse = historyData?.data as
    | PredictionHistoryResponseDto
    | undefined;
  const history = historyResponse?.history ?? [];

  const riskColors: Record<string, string> = {
    LOW: "green",
    MEDIUM: "yellow",
    HIGH: "orange",
    "VERY HIGH": "red",
  };

  const tabs: { key: TabType; label: string }[] = [
    { key: "upcoming", label: t("upcoming") },
    { key: "value-bets", label: t("value-bets") },
    { key: "history", label: t("history") },
  ];

  return (
    <SlideUp>
      <Box>
        <Heading as="h1" size="xl" fontWeight="bold" mb={6}>
          {t("title")}
        </Heading>

        {/* Tabs */}
        <HStack gap={2} mb={6} overflowX="auto" pb={1}>
          {tabs.map((tab) => (
            <Button
              key={tab.key}
              variant={activeTab === tab.key ? "solid" : "outline"}
              colorPalette={activeTab === tab.key ? "primary" : "gray"}
              size="sm"
              borderRadius="full"
              onClick={() => setActiveTab(tab.key)}
              flexShrink={0}
            >
              {tab.label}
            </Button>
          ))}
        </HStack>

        {/* Upcoming Predictions Tab */}
        {activeTab === "upcoming" &&
          (upcomingLoading ? (
            <Flex justify="center" py={16}>
              <Spinner size="lg" color="primary.500" />
            </Flex>
          ) : upcomingPredictions.length > 0 ? (
            <StaggerContainer>
              <SimpleGrid columns={{ base: 1, md: 2 }} gap={4}>
                {upcomingPredictions.map(
                  (pred: MatchPredictionDto, idx: number) => {
                    const sport = getPredictionSport(pred);
                    return (
                      <StaggerItem key={idx}>
                        <Card.Root
                          bg={cardBg}
                          borderColor={borderColor}
                          borderRadius="xl"
                          cursor="pointer"
                          _hover={{ shadow: "lg", borderColor: "primary.300" }}
                          transition="all 0.2s"
                          onClick={() =>
                            router.push(`/matches/${pred.match_info.match_id}`)
                          }
                        >
                          <Card.Body>
                            <Flex justify="space-between" align="center" mb={3}>
                              <Text fontSize="sm" fontWeight="bold">
                                {pred.match_info.home_team} vs{" "}
                                {pred.match_info.away_team}
                              </Text>
                              <HStack gap={2}>
                                <Badge
                                  colorPalette={
                                    sport === "basketball" ? "orange" : "blue"
                                  }
                                  variant="subtle"
                                  fontSize="2xs"
                                  borderRadius="full"
                                >
                                  {tMatches(sport)}
                                </Badge>
                                <Badge
                                  colorPalette={
                                    riskColors[
                                      pred.risk?.level?.toUpperCase()
                                    ] || "gray"
                                  }
                                  variant="subtle"
                                  fontSize="2xs"
                                  borderRadius="full"
                                >
                                  {pred.risk?.level}
                                </Badge>
                              </HStack>
                            </Flex>

                            {pred.main_pick && (
                              <Box
                                p={3}
                                bg="primary.subtle"
                                borderRadius="lg"
                                mb={3}
                              >
                                <Flex justify="space-between" align="center">
                                  <VStack gap={0} align="flex-start">
                                    <Text fontSize="xs" color="fg.muted">
                                      {t("main-pick")}
                                    </Text>
                                    <Text fontSize="md" fontWeight="bold">
                                      {pred.main_pick.pick}
                                    </Text>
                                  </VStack>
                                  <VStack gap={0} align="flex-end">
                                    <Text fontSize="xs" color="fg.muted">
                                      {t("confidence")}
                                    </Text>
                                    <Text
                                      fontSize="md"
                                      fontWeight="bold"
                                      color="primary.fg"
                                    >
                                      {Math.round(
                                        pred.main_pick.unified_score ??
                                          pred.main_pick.calibrated_confidence ??
                                          pred.main_pick.confidence,
                                      )}
                                      %
                                    </Text>
                                  </VStack>
                                </Flex>
                              </Box>
                            )}

                            <HStack justify="space-between">
                              <Text fontSize="xs" color="fg.muted">
                                {t("data-quality")}:{" "}
                                {Math.round(
                                  (pred.data_quality?.score ?? 0) * 100,
                                )}
                                %
                              </Text>
                              <Text fontSize="xs" color="fg.muted">
                                {pred.model_version}
                              </Text>
                            </HStack>
                          </Card.Body>
                        </Card.Root>
                      </StaggerItem>
                    );
                  },
                )}
              </SimpleGrid>
            </StaggerContainer>
          ) : (
            <Flex justify="center" py={16}>
              <Text color="fg.muted">{t("no-predictions")}</Text>
            </Flex>
          ))}

        {/* Value Bets Tab */}
        {activeTab === "value-bets" &&
          (valueBetsLoading ? (
            <Flex justify="center" py={16}>
              <Spinner size="lg" color="primary.500" />
            </Flex>
          ) : valueBets.length > 0 ? (
            <StaggerContainer>
              <SimpleGrid columns={{ base: 1, md: 2, lg: 3 }} gap={4}>
                {valueBets.map((vb: ValueBetDto, idx: number) => (
                  <StaggerItem key={idx}>
                    <Card.Root
                      bg={cardBg}
                      borderColor={borderColor}
                      borderRadius="xl"
                    >
                      <Card.Body>
                        <Text fontSize="sm" color="fg.muted" truncate mb={2}>
                          {vb.matchName}
                        </Text>
                        <Flex justify="space-between" align="center" mb={2}>
                          <Text fontSize="lg" fontWeight="bold">
                            {vb.prediction}
                          </Text>
                          <Badge
                            colorPalette="primary"
                            variant="subtle"
                            borderRadius="full"
                          >
                            {vb.odd.toFixed(2)}
                          </Badge>
                        </Flex>
                        <HStack justify="space-between">
                          <Badge
                            colorPalette="green"
                            variant="solid"
                            fontSize="xs"
                            borderRadius="full"
                          >
                            EV+ {(vb.expectedValue * 100).toFixed(0)}%
                          </Badge>
                          <Text fontSize="xs" color="fg.muted">
                            {t("confidence")}: {Math.round(vb.confidence * 100)}
                            %
                          </Text>
                        </HStack>
                      </Card.Body>
                    </Card.Root>
                  </StaggerItem>
                ))}
              </SimpleGrid>
            </StaggerContainer>
          ) : (
            <Flex justify="center" py={16}>
              <Text color="fg.muted">{t("no-predictions")}</Text>
            </Flex>
          ))}

        {/* History Tab */}
        {activeTab === "history" &&
          (historyLoading ? (
            <Flex justify="center" py={16}>
              <Spinner size="lg" color="primary.500" />
            </Flex>
          ) : history.length > 0 ? (
            <StaggerContainer>
              <VStack gap={3} align="stretch">
                {history.map((item: Record<string, unknown>, idx: number) => (
                  <StaggerItem key={idx}>
                    <Card.Root
                      bg={cardBg}
                      borderColor={borderColor}
                      borderRadius="xl"
                    >
                      <Card.Body>
                        <Flex justify="space-between" align="center">
                          <VStack gap={0} align="flex-start">
                            <Text fontSize="sm" fontWeight="bold">
                              {String(item.homeTeam ?? "")} vs{" "}
                              {String(item.awayTeam ?? "")}
                            </Text>
                            <Text fontSize="xs" color="fg.muted">
                              {String(item.pick ?? "")}
                            </Text>
                          </VStack>
                          <VStack gap={0} align="flex-end">
                            <Badge
                              colorPalette={
                                item.result === "correct"
                                  ? "green"
                                  : item.result === "incorrect"
                                    ? "red"
                                    : "gray"
                              }
                              variant="subtle"
                              fontSize="xs"
                              borderRadius="full"
                            >
                              {String(item.result ?? "pending")}
                            </Badge>
                            <Text fontSize="xs" color="fg.muted">
                              {typeof item.confidence === "number"
                                ? `${Math.round(item.confidence * 100)}%`
                                : "—"}
                            </Text>
                          </VStack>
                        </Flex>
                      </Card.Body>
                    </Card.Root>
                  </StaggerItem>
                ))}
              </VStack>
            </StaggerContainer>
          ) : (
            <Flex justify="center" py={16}>
              <Text color="fg.muted">{t("no-predictions")}</Text>
            </Flex>
          ))}
      </Box>
    </SlideUp>
  );
}
