"use client";

import {
  Box,
  Flex,
  Heading,
  Text,
  Card,
  VStack,
  HStack,
  Badge,
  Spinner,
  Separator,
  Button,
} from "@chakra-ui/react";
import { useTranslations } from "next-intl";
import { useColorModeValue } from "@/components/ui/color-mode";
import { SlideUp, StaggerContainer, StaggerItem } from "@/components/motion";
import { useCouponHistory } from "@/lib/api/coupons/use-hooks";
import type { CouponResponseDto, CouponItemDto } from "@/lib/api/coupons/types";
import { useState } from "react";

type FilterType = "all" | "pending" | "won" | "lost";

export default function CouponHistoryContent() {
  const t = useTranslations("coupons");
  const tCommon = useTranslations("common");
  const [filter, setFilter] = useState<FilterType>("all");

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

  const { data, isLoading } = useCouponHistory();
  const historyData = data?.data as
    | { coupons?: CouponResponseDto[] }
    | undefined;
  const allCoupons: CouponResponseDto[] = historyData?.coupons ?? [];

  const filteredCoupons =
    filter === "all"
      ? allCoupons
      : allCoupons.filter(
          (c: CouponResponseDto) => c.status?.toLowerCase() === filter,
        );

  const statusColors: Record<string, string> = {
    pending: "yellow",
    won: "green",
    lost: "red",
  };

  const filters: { key: FilterType; label: string }[] = [
    { key: "all", label: tCommon("all") },
    { key: "pending", label: t("pending") },
    { key: "won", label: t("won") },
    { key: "lost", label: t("lost") },
  ];

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

        {/* Filters */}
        <HStack gap={2} mb={6} overflowX="auto" pb={1}>
          {filters.map((f) => (
            <Button
              key={f.key}
              variant={filter === f.key ? "solid" : "outline"}
              colorPalette={filter === f.key ? "primary" : "gray"}
              size="sm"
              borderRadius="full"
              onClick={() => setFilter(f.key)}
              flexShrink={0}
            >
              {f.label}
            </Button>
          ))}
        </HStack>

        {isLoading ? (
          <Flex justify="center" py={16}>
            <Spinner size="lg" color="primary.500" />
          </Flex>
        ) : filteredCoupons.length > 0 ? (
          <StaggerContainer>
            <VStack gap={4} align="stretch">
              {filteredCoupons.map((coupon: CouponResponseDto, idx: number) => (
                <StaggerItem key={coupon.id ?? idx}>
                  <Card.Root
                    bg={cardBg}
                    borderColor={borderColor}
                    borderRadius="xl"
                  >
                    <Card.Header pb={2}>
                      <Flex justify="space-between" align="center">
                        <HStack gap={2}>
                          <Text fontSize="sm" fontWeight="bold">
                            {t("coupon")} #{coupon.id?.slice(-6) || idx + 1}
                          </Text>
                          <Badge
                            colorPalette={
                              statusColors[
                                coupon.status?.toLowerCase() ?? ""
                              ] || "gray"
                            }
                            variant="subtle"
                            fontSize="xs"
                            borderRadius="full"
                          >
                            {coupon.status || "—"}
                          </Badge>
                        </HStack>
                        <VStack gap={0} align="flex-end">
                          <Text fontSize="xs" color="fg.muted">
                            {t("total-odd")}
                          </Text>
                          <Text fontSize="sm" fontWeight="bold">
                            {coupon.totalOdd?.toFixed(2) || "—"}
                          </Text>
                        </VStack>
                      </Flex>
                    </Card.Header>
                    <Card.Body pt={0}>
                      {coupon.items?.map(
                        (item: CouponItemDto, itemIdx: number) => (
                          <Box key={itemIdx}>
                            {itemIdx > 0 && <Separator my={2} />}
                            <Flex justify="space-between" align="center">
                              <VStack gap={0} align="flex-start">
                                <Text fontSize="xs" fontWeight="semibold">
                                  {item.matchId}
                                </Text>
                                <Text fontSize="2xs" color="fg.muted">
                                  {item.market}: {item.pick}
                                </Text>
                              </VStack>
                              <Badge
                                colorPalette="primary"
                                variant="subtle"
                                fontSize="2xs"
                                borderRadius="full"
                              >
                                {item.odd?.toFixed(2)}
                              </Badge>
                            </Flex>
                          </Box>
                        ),
                      )}

                      {coupon.strategy && (
                        <Flex
                          mt={3}
                          pt={2}
                          borderTopWidth="1px"
                          borderColor={borderColor}
                          justify="space-between"
                        >
                          <Text fontSize="2xs" color="fg.muted">
                            {t("strategy")}: {coupon.strategy}
                          </Text>
                          <Text fontSize="2xs" color="fg.muted">
                            {coupon.createdAt &&
                              new Date(coupon.createdAt).toLocaleDateString(
                                "tr-TR",
                              )}
                          </Text>
                        </Flex>
                      )}
                    </Card.Body>
                  </Card.Root>
                </StaggerItem>
              ))}
            </VStack>
          </StaggerContainer>
        ) : (
          <Flex justify="center" py={16}>
            <Text color="fg.muted">{t("no-coupons")}</Text>
          </Flex>
        )}
      </Box>
    </SlideUp>
  );
}
