"use client";

import {
  Box,
  Flex,
  Text,
  Badge,
  HStack,
  VStack,
  Image,
} from "@chakra-ui/react";
import { useLocale, useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { useSession } from "next-auth/react";
import { motion } from "framer-motion";
import { slideUpVariants } from "@/components/motion";
import type { MatchResponseDto } from "@/lib/api/matches/types";
import { useColorModeValue } from "@/components/ui/color-mode";
import { useState } from "react";
import { LoginModal } from "@/components/auth/login-modal";

interface MatchCardProps {
  match: MatchResponseDto;
}

const MotionBox = motion.create(Box);

export default function MatchCard({ match }: MatchCardProps) {
  const t = useTranslations("matches");
  const tAuth = useTranslations("auth");
  const locale = useLocale();
  const router = useRouter();
  const { data: session } = useSession();
  const [loginModalOpen, setLoginModalOpen] = useState(false);

  const cardBg = useColorModeValue("white", "gray.800");
  const cardBorder = useColorModeValue("gray.100", "gray.700");
  const hoverBg = useColorModeValue("gray.50", "gray.750");
  const hoverBorder = useColorModeValue("primary.200", "primary.500");

  const isLive = match.status === "LIVE";
  const isFinished = match.status === "Finished";

  const statusColor = isLive ? "red" : isFinished ? "gray" : "green";
  const statusText = isLive
    ? t("live")
    : isFinished
      ? t("finished")
      : t("not-started");

  const handleClick = () => {
    if (!session) {
      setLoginModalOpen(true);
      return;
    }
    router.push(`/matches/${match.id}`);
  };

  // Date handling from timestamp (mstUtc)
  const matchDate = new Date(match.mstUtc);

  return (
    <>
      <MotionBox
        variants={slideUpVariants}
        bg={cardBg}
        borderWidth="1px"
        borderColor={cardBorder}
        borderRadius="xl"
        p={4}
        cursor="pointer"
        onClick={handleClick}
        transition={{ duration: 0.25 }}
        _hover={{
          bg: hoverBg,
          borderColor: hoverBorder,
          transform: "translateY(-3px)",
          shadow: "xl",
        }}
        role="button"
        tabIndex={0}
        aria-label={`${match.homeTeamName} vs ${match.awayTeamName}`}
      >
        {/* Status Badge */}
        <Flex justify="space-between" align="center" mb={3}>
          <Badge
            colorPalette={statusColor}
            variant="subtle"
            px={2}
            py={0.5}
            borderRadius="full"
            fontSize="xs"
            fontWeight="bold"
          >
            {isLive && (
              <Box
                as="span"
                display="inline-block"
                w="6px"
                h="6px"
                borderRadius="full"
                bg="red.500"
                mr={1.5}
                animation="pulse 1.5s ease-in-out infinite"
              />
            )}
            {statusText}
          </Badge>

          <Text fontSize="xs" color="fg.muted">
            {matchDate.toLocaleDateString(locale, {
              day: "2-digit",
              month: "short",
              hour: "2-digit",
              minute: "2-digit",
            })}
          </Text>
        </Flex>

        {/* Teams */}
        <HStack gap={3} justify="space-between">
          {/* Home Team */}
          <VStack gap={1} flex={1} align="center" minW={0}>
            {match.homeTeamLogo ? (
              <Image
                src={match.homeTeamLogo}
                alt={match.homeTeamName}
                boxSize="40px"
                objectFit="contain"
              />
            ) : (
              <Flex
                boxSize="40px"
                bg="primary.subtle"
                borderRadius="full"
                align="center"
                justify="center"
              >
                <Text fontSize="lg" fontWeight="bold" color="primary.fg">
                  {match.homeTeamName?.charAt(0) || "H"}
                </Text>
              </Flex>
            )}
            <Text
              fontSize="sm"
              fontWeight="semibold"
              textAlign="center"
              truncate
              maxW="100%"
            >
              {match.homeTeamName}
            </Text>
          </VStack>

          {/* Score or VS */}
          <VStack gap={0} flexShrink={0}>
            {(isLive || isFinished) &&
            match.scoreHome !== undefined &&
            match.scoreAway !== undefined ? (
              <HStack gap={2}>
                <Text
                  fontSize="2xl"
                  fontWeight="900"
                  color={isLive ? "red.500" : "fg"}
                >
                  {match.scoreHome}
                </Text>
                <Text fontSize="lg" color="fg.muted">
                  -
                </Text>
                <Text
                  fontSize="2xl"
                  fontWeight="900"
                  color={isLive ? "red.500" : "fg"}
                >
                  {match.scoreAway}
                </Text>
              </HStack>
            ) : (
              <Text fontSize="md" fontWeight="bold" color="fg.muted">
                {t("vs")}
              </Text>
            )}
          </VStack>

          {/* Away Team */}
          <VStack gap={1} flex={1} align="center" minW={0}>
            {match.awayTeamLogo ? (
              <Image
                src={match.awayTeamLogo}
                alt={match.awayTeamName}
                boxSize="40px"
                objectFit="contain"
              />
            ) : (
              <Flex
                boxSize="40px"
                bg="primary.subtle"
                borderRadius="full"
                align="center"
                justify="center"
              >
                <Text fontSize="lg" fontWeight="bold" color="primary.fg">
                  {match.awayTeamName?.charAt(0) || "A"}
                </Text>
              </Flex>
            )}
            <Text
              fontSize="sm"
              fontWeight="semibold"
              textAlign="center"
              truncate
              maxW="100%"
            >
              {match.awayTeamName}
            </Text>
          </VStack>
        </HStack>

        {/* League Info */}
        {(match.leagueName || match.countryName) && (
          <Flex
            mt={3}
            pt={2}
            borderTopWidth="1px"
            borderColor={cardBorder}
            justify="center"
            align="center"
            gap={1.5}
          >
            {/* Flag handling if available in flat response, otherwise skip or pass from parent */}
            <Text fontSize="xs" color="fg.muted" truncate>
              {match.countryName && `${match.countryName} • `}
              {match.leagueName}
            </Text>
          </Flex>
        )}

        {/* Auth hint for unauthenticated users */}
        {!session && (
          <Flex
            mt={2}
            pt={2}
            borderTopWidth="1px"
            borderColor={cardBorder}
            justify="center"
            align="center"
          >
            <Text fontSize="xs" color="orange.500" fontWeight="semibold">
              🔒 {tAuth("login-required-title")}
            </Text>
          </Flex>
        )}
      </MotionBox>

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