"use client";

import {
  Box,
  SimpleGrid,
  Text,
  Badge,
  Card,
  VStack,
  Flex,
} from "@chakra-ui/react";
import { useColorModeValue } from "@/components/ui/color-mode";

interface OddsCardProps {
  odds?: Record<string, Record<string, { odd: string }>>;
}

interface MarketBlockProps {
  title: string;
  selections: Record<string, { odd: string }>;
}

function MarketBlock({ title, selections }: MarketBlockProps) {
  const bg = useColorModeValue("gray.50", "gray.800");
  const borderColor = useColorModeValue("gray.200", "gray.700");
  const selectionBg = useColorModeValue("white", "gray.700");

  // Sort selections based on common market patterns
  const sortedKeys = Object.keys(selections).sort((a, b) => {
    // MS: 1, X, 2
    if (["1", "X", "2"].includes(a) && ["1", "X", "2"].includes(b)) {
      const order = ["1", "X", "2"];
      return order.indexOf(a) - order.indexOf(b);
    }
    // Alt/Üst: Alt, Üst
    if (["Alt", "Üst"].includes(a) && ["Alt", "Üst"].includes(b)) {
      return a === "Alt" ? -1 : 1; // Alt first
    }
    // KG: Var, Yok
    if (["Var", "Yok"].includes(a) && ["Var", "Yok"].includes(b)) {
      return a === "Var" ? -1 : 1; // Var first
    }
    return a.localeCompare(b);
  });

  return (
    <Box
      bg={bg}
      borderWidth="1px"
      borderColor={borderColor}
      borderRadius="md"
      overflow="hidden"
    >
      <Box px={3} py={1.5} borderBottomWidth="1px" borderColor={borderColor}>
        <Text
          fontSize="xs"
          fontWeight="bold"
          color="fg.muted"
          textTransform="uppercase"
        >
          {title}
        </Text>
      </Box>
      <Flex p={2} gap={2} wrap="wrap">
        {sortedKeys.map((key) => (
          <Flex
            key={key}
            direction="column"
            align="center"
            justify="center"
            bg={selectionBg}
            borderWidth="1px"
            borderColor={borderColor}
            borderRadius="sm"
            minW="50px"
            py={1}
            px={2}
            flex={1}
          >
            <Text fontSize="xs" color="fg.muted" mb={0.5}>
              {key}
            </Text>
            <Text fontSize="sm" fontWeight="bold" color="primary.500">
              {Number(selections[key].odd).toFixed(2)}
            </Text>
          </Flex>
        ))}
      </Flex>
    </Box>
  );
}

export default function OddsCard({ odds }: OddsCardProps) {
  const cardBg = useColorModeValue("white", "gray.900");
  const borderColor = useColorModeValue("gray.100", "gray.800");

  if (!odds || Object.keys(odds).length === 0) {
    return null;
  }

  // Define priority markets to show at the top
  const PRIORITY_MARKETS = [
    "Maç Sonucu",
    "2.5 Alt/Üst",
    "Karşılıklı Gol",
    "İlk Yarı Sonucu",
    "1. Yarı Sonucu",
    "Kart",
    "Korner",
  ];

  const marketKeys = Object.keys(odds);
  const priorityKeys = marketKeys.filter((k) =>
    PRIORITY_MARKETS.some((pm) => k.includes(pm)),
  );
  const otherKeys = marketKeys.filter(
    (k) => !PRIORITY_MARKETS.some((pm) => k.includes(pm)),
  );

  // Group similar markets if needed, but simple list for now

  return (
    <Card.Root bg={cardBg} borderColor={borderColor} borderRadius="xl" mb={6}>
      <Card.Body>
        <VStack align="stretch" gap={4}>
          <Text fontSize="lg" fontWeight="bold">
            Canlı İddaa Oranları
          </Text>

          {/* Priority Markets Grid */}
          {priorityKeys.length > 0 && (
            <SimpleGrid columns={{ base: 1, md: 2 }} gap={4}>
              {priorityKeys.map((key) => (
                <MarketBlock key={key} title={key} selections={odds[key]} />
              ))}
            </SimpleGrid>
          )}

          {/* Other Markets - Show ALL */}
          {otherKeys.length > 0 && (
            <SimpleGrid
              columns={{ base: 1, md: 2, lg: 3 }}
              gap={4}
              mt={priorityKeys.length > 0 ? 2 : 0}
            >
              {otherKeys.map((key) => (
                <MarketBlock key={key} title={key} selections={odds[key]} />
              ))}
            </SimpleGrid>
          )}
        </VStack>
      </Card.Body>
    </Card.Root>
  );
}
