"use client";

import {
  Box,
  Flex,
  Heading,
  Text,
  Card,
  VStack,
  HStack,
  Badge,
  Spinner,
  Button,
  Table,
} from "@chakra-ui/react";
import { useTranslations } from "next-intl";
import { useColorModeValue } from "@/components/ui/color-mode";
import { SlideUp, StaggerContainer, StaggerItem } from "@/components/motion";
import {
  useBulletins,
  useGeneratePrediction,
  useSyncBulletin,
  useRolloverHistory,
} from "@/lib/api/spor-toto/use-hooks";
import { useQueryClient } from "@tanstack/react-query";
import { UsersQueryKeys } from "@/lib/api/users/use-hooks";
import type {
  SporTotoBulletinDto,
  SporTotoPredictionResultDto,
} from "@/lib/api/spor-toto/service";
import {
  LuRefreshCw,
  LuSparkles,
  LuTrendingUp,
  LuTicket,
} from "react-icons/lu";
import { useState } from "react";
import { toaster } from "@/components/ui/feedback/toaster";
import {
  NativeSelectRoot,
  NativeSelectField,
} from "@/components/ui/forms/native-select";

type PredictionStrategy =
  | "CONSERVATIVE"
  | "BALANCED"
  | "AGGRESSIVE"
  | "FORMULA_6PCT";

export default function SporTotoContent() {
  const t = useTranslations("spor-toto");
  const tCommon = useTranslations("common");

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

  const [selectedBulletin, setSelectedBulletin] = useState<string>("");
  const [strategy, setStrategy] = useState<PredictionStrategy>("BALANCED");

  const bulletins = useBulletins();
  const rolloverHistory = useRolloverHistory(10);
  const syncBulletin = useSyncBulletin();
  const generatePrediction = useGeneratePrediction();
  const queryClient = useQueryClient();
  const toast = (opts: { title: string; status: string }) =>
    toaster.create({
      title: opts.title,
      type: opts.status as "success" | "warning" | "error" | "info" | "loading",
    });

  const handleSync = async () => {
    await syncBulletin.mutateAsync();
    toast({
      title: t("sync-success"),
      status: "success",
    });
    bulletins.refetch();
  };

  const handlePredict = async () => {
    if (!selectedBulletin) {
      toast({
        title: t("select-bulletin"),
        status: "warning",
      });
      return;
    }
    const result = await generatePrediction.mutateAsync({
      bulletinId: selectedBulletin,
      strategy,
    });
    queryClient.invalidateQueries({ queryKey: UsersQueryKeys.me() });
    toast({
      title: t("prediction-generated"),
      status: "success",
    });
  };

  const strategies: {
    value: PredictionStrategy;
    label: string;
    desc: string;
  }[] = [
    {
      value: "CONSERVATIVE",
      label: t("strategy-conservative"),
      desc: t("strategy-conservative-desc"),
    },
    {
      value: "BALANCED",
      label: t("strategy-balanced"),
      desc: t("strategy-balanced-desc"),
    },
    {
      value: "AGGRESSIVE",
      label: t("strategy-aggressive"),
      desc: t("strategy-aggressive-desc"),
    },
    {
      value: "FORMULA_6PCT",
      label: t("strategy-formula"),
      desc: t("strategy-formula-desc"),
    },
  ];

  return (
    <SlideUp>
      <Box maxW="6xl" mx="auto">
        <Flex justify="space-between" align="center" mb={6}>
          <Heading as="h1" size="xl" fontWeight="bold">
            {t("title")}
          </Heading>
          <Button
            variant="outline"
            size="sm"
            onClick={handleSync}
            loading={syncBulletin.isPending}
          >
            <LuRefreshCw />
            {t("sync-bulletins")}
          </Button>
        </Flex>

        <StaggerContainer>
          <Flex gap={6} direction={{ base: "column", lg: "row" }}>
            {/* Left Column - Bulletin Selection & Prediction */}
            <Box flex={2}>
              {/* Bulletin Selection */}
              <Card.Root
                bg={cardBg}
                borderColor={borderColor}
                borderRadius="xl"
                mb={6}
              >
                <Card.Header>
                  <Heading as="h3" size="sm">
                    {t("select-bulletin")}
                  </Heading>
                </Card.Header>
                <Card.Body pt={0}>
                  {bulletins.isLoading ? (
                    <Flex justify="center" py={4}>
                      <Spinner size="sm" color="primary.500" />
                    </Flex>
                  ) : (
                    <NativeSelectRoot>
                      <NativeSelectField
                        value={selectedBulletin}
                        onChange={(e) => setSelectedBulletin(e.target.value)}
                        placeholder={t("choose-bulletin")}
                      >
                        {bulletins.data?.data?.map((b: SporTotoBulletinDto) => (
                          <option key={b.id} value={b.id}>
                            {t("bulletin-label", {
                              cycle: b.gameCycleNo,
                              date: new Date(b.drawDate).toLocaleDateString(),
                            })}
                          </option>
                        ))}
                      </NativeSelectField>
                    </NativeSelectRoot>
                  )}
                </Card.Body>
              </Card.Root>

              {/* Strategy Selection */}
              <Card.Root
                bg={cardBg}
                borderColor={borderColor}
                borderRadius="xl"
                mb={6}
              >
                <Card.Header>
                  <Heading as="h3" size="sm">
                    {t("choose-strategy")}
                  </Heading>
                </Card.Header>
                <Card.Body pt={0}>
                  <VStack gap={3}>
                    {strategies.map((s) => (
                      <Card.Root
                        key={s.value}
                        borderWidth={strategy === s.value ? "2px" : "1px"}
                        borderColor={
                          strategy === s.value ? "primary.500" : borderColor
                        }
                        cursor="pointer"
                        onClick={() => setStrategy(s.value)}
                        _hover={{ borderColor: "primary.300" }}
                      >
                        <Card.Body py={3}>
                          <Flex justify="space-between" align="center">
                            <VStack align="start" gap={0}>
                              <Text fontWeight="semibold">{s.label}</Text>
                              <Text fontSize="xs" color="fg.muted">
                                {s.desc}
                              </Text>
                            </VStack>
                            <Badge
                              colorScheme={
                                strategy === s.value ? "primary" : "gray"
                              }
                            >
                              {strategy === s.value ? <LuSparkles /> : null}
                              {strategy === s.value ? t("selected") : ""}
                            </Badge>
                          </Flex>
                        </Card.Body>
                      </Card.Root>
                    ))}
                  </VStack>
                  <Button
                    mt={4}
                    w="full"
                    onClick={handlePredict}
                    loading={generatePrediction.isPending}
                  >
                    <LuSparkles /> {t("generate-prediction")}
                  </Button>
                </Card.Body>
              </Card.Root>

              {/* Bulletins List */}
              <Card.Root
                bg={cardBg}
                borderColor={borderColor}
                borderRadius="xl"
              >
                <Card.Header>
                  <Heading as="h3" size="sm">
                    {t("bulletin-history")}
                  </Heading>
                </Card.Header>
                <Card.Body pt={0}>
                  {bulletins.isLoading ? (
                    <Flex justify="center" py={6}>
                      <Spinner size="sm" color="primary.500" />
                    </Flex>
                  ) : (
                    <Table.Root size="sm">
                      <Table.Header>
                        <Table.Row>
                          <Table.ColumnHeader>
                            {t("cycle-no")}
                          </Table.ColumnHeader>
                          <Table.ColumnHeader>
                            {t("draw-date")}
                          </Table.ColumnHeader>
                          <Table.ColumnHeader>{t("status")}</Table.ColumnHeader>
                          <Table.ColumnHeader>
                            {t("matches")}
                          </Table.ColumnHeader>
                        </Table.Row>
                      </Table.Header>
                      <Table.Body>
                        {bulletins.data?.data?.map((b: SporTotoBulletinDto) => (
                          <Table.Row
                            key={b.id}
                            cursor="pointer"
                            onClick={() => setSelectedBulletin(b.id)}
                            bg={
                              selectedBulletin === b.id
                                ? "primary.50"
                                : "transparent"
                            }
                          >
                            <Table.Cell>{b.gameCycleNo}</Table.Cell>
                            <Table.Cell>
                              {new Date(b.drawDate).toLocaleDateString()}
                            </Table.Cell>
                            <Table.Cell>
                              <Badge
                                colorScheme={
                                  b.status === "COMPLETED"
                                    ? "green"
                                    : b.status === "ACTIVE"
                                      ? "blue"
                                      : "gray"
                                }
                              >
                                {b.status}
                              </Badge>
                            </Table.Cell>
                            <Table.Cell>{b.matches?.length || 0}</Table.Cell>
                          </Table.Row>
                        ))}
                      </Table.Body>
                    </Table.Root>
                  )}
                </Card.Body>
              </Card.Root>
            </Box>

            {/* Right Column - Rollover Stats */}
            <Box flex={1}>
              <Card.Root
                bg={cardBg}
                borderColor={borderColor}
                borderRadius="xl"
                mb={6}
              >
                <Card.Header>
                  <Heading as="h3" size="sm">
                    <HStack gap={2}>
                      <LuTrendingUp />
                      <Text>{t("rollover-stats")}</Text>
                    </HStack>
                  </Heading>
                </Card.Header>
                <Card.Body pt={0}>
                  {rolloverHistory.isLoading ? (
                    <Spinner size="sm" />
                  ) : (
                    <VStack gap={3}>
                      {rolloverHistory.data?.data
                        ?.slice(0, 5)
                        .map(
                          (item: {
                            gameCycleNo: number;
                            rolloverAmount: number;
                            drawDate: string;
                          }) => (
                            <Flex
                              key={item.gameCycleNo}
                              justify="space-between"
                              w="full"
                              py={2}
                              borderBottom="1px"
                              borderColor={borderColor}
                            >
                              <VStack align="start" gap={0}>
                                <Text fontSize="sm" fontWeight="semibold">
                                  {t("cycle-no-short", {
                                    cycle: item.gameCycleNo,
                                  })}
                                </Text>
                                <Text fontSize="xs" color="fg.muted">
                                  {new Date(item.drawDate).toLocaleDateString()}
                                </Text>
                              </VStack>
                              <Badge colorScheme="orange">
                                <HStack gap={1}>
                                  <LuTicket />
                                  <Text>
                                    {new Intl.NumberFormat("tr-TR", {
                                      style: "currency",
                                      currency: "TRY",
                                    }).format(item.rolloverAmount)}
                                  </Text>
                                </HStack>
                              </Badge>
                            </Flex>
                          ),
                        )}
                    </VStack>
                  )}
                </Card.Body>
              </Card.Root>
            </Box>
          </Flex>
        </StaggerContainer>
      </Box>
    </SlideUp>
  );
}
