"use client";

import {
  Box,
  Flex,
  Heading,
  Text,
  VStack,
  HStack,
  SimpleGrid,
  Spinner,
  Card,
} from "@chakra-ui/react";
import { useTranslations } from "next-intl";
import { useColorModeValue } from "@/components/ui/color-mode";
import { useSession } from "next-auth/react";
import { useState } from "react";
import { useSubscriptionPlans } from "@/lib/api/subscriptions/use-hooks";
import { usePaddleCheckout } from "@/lib/paddle";
import { PricingCard } from "@/components/subscription";
import { LoginModal } from "@/components/auth/login-modal";
import { SlideUp } from "@/components/motion";
import { SegmentedControl } from "@/components/ui/forms/segmented-control";
import type {
  PlanInfo,
  PlanType,
  BillingInterval,
} from "@/lib/api/subscriptions/types";
import { LuMessageCircleQuestion, LuChevronDown } from "react-icons/lu";

/** Static fallback plans used when the backend is not reachable */
const FALLBACK_PLANS: readonly PlanInfo[] = [
  {
    id: "free" as PlanType,
    name: "Free",
    description: "",
    monthlyPrice: 0,
    yearlyPrice: 0,
    currency: "TRY",
    features: [],
    limits: { maxAnalyses: 3, maxCoupons: 1 },
    highlighted: false,
  },
  {
    id: "plus" as PlanType,
    name: "Plus",
    description: "",
    monthlyPrice: 149,
    yearlyPrice: 1490,
    currency: "TRY",
    features: [],
    limits: { maxAnalyses: 15, maxCoupons: 5 },
    highlighted: true,
  },
  {
    id: "premium" as PlanType,
    name: "Premium",
    description: "",
    monthlyPrice: 349,
    yearlyPrice: 3490,
    currency: "TRY",
    features: [],
    limits: { maxAnalyses: 999, maxCoupons: 999 },
    highlighted: false,
  },
] as const;

/**
 * Main pricing page content.
 * Fetches plans from API, shows monthly/yearly toggle,
 * renders pricing cards and FAQ section.
 */
export default function PricingContent() {
  const t = useTranslations("pricing");
  const { data: session } = useSession();
  const { data: plansData, isLoading } = useSubscriptionPlans();
  const { startCheckout, isLoading: checkoutLoading } = usePaddleCheckout();

  const [isYearly, setIsYearly] = useState(false);
  const [loginModalOpen, setLoginModalOpen] = useState(false);
  const [selectedCheckoutPlan, setSelectedCheckoutPlan] =
    useState<PlanType | null>(null);

  const subtitleColor = useColorModeValue("gray.600", "gray.400");

  const currentPlan = session?.user?.subscriptionPlan ?? "free";
  const plans = plansData?.data ?? FALLBACK_PLANS;

  // Enrich plans with i18n translated names/descriptions/features
  const enrichedPlans: readonly PlanInfo[] = plans.map((plan) => {
    const planKey = String(plan.id).toLowerCase() as
      | "free"
      | "plus"
      | "premium";
    const featureKeys = getFeatureKeysForPlan(planKey, plan.limits);

    return {
      ...plan,
      name: t(`plan.${planKey}.name`),
      description: t(`plan.${planKey}.description`),
      features: featureKeys.map((key) => {
        const match = key.match(/^(\d+)\s+(.+)$/);
        if (match) {
          const count = match[1];
          const transKey = match[2];
          return `${count} ${t(`feature.${transKey}`)}`;
        }

        if (key.startsWith("unlimited-")) {
          const transKey = key.replace("unlimited-", "");
          return `${t("feature.unlimited")} ${t(`feature.${transKey}`)}`;
        }

        return t(`feature.${key}`);
      }),
    };
  });

  const handlePlanSelect = (plan: PlanInfo) => {
    if (plan.id === "free") return;

    if (!session) {
      setLoginModalOpen(true);
      return;
    }

    setSelectedCheckoutPlan(plan.id);
    const interval: BillingInterval = isYearly
      ? ("yearly" as BillingInterval)
      : ("monthly" as BillingInterval);
    startCheckout(plan.id, interval);
  };

  const faqItems = [
    { q: t("faq.q1"), a: t("faq.a1") },
    { q: t("faq.q2"), a: t("faq.a2") },
    { q: t("faq.q3"), a: t("faq.a3") },
    { q: t("faq.q4"), a: t("faq.a4") },
  ];

  return (
    <>
      <SlideUp>
        <Box py={{ base: 8, md: 16 }}>
          {/* Hero Section */}
          <VStack gap={4} textAlign="center" mb={{ base: 10, md: 14 }}>
            <Heading
              as="h1"
              fontSize={{ base: "3xl", md: "4xl", lg: "5xl" }}
              fontWeight="900"
              letterSpacing="-0.03em"
              lineHeight="1.1"
            >
              {t("title")}
            </Heading>
            <Text
              fontSize={{ base: "md", md: "lg" }}
              color={subtitleColor}
              maxW="xl"
            >
              {t("subtitle")}
            </Text>

            {/* Monthly / Yearly Toggle */}
            <HStack
              gap={3}
              bg={useColorModeValue("gray.50", "gray.900")}
              p={1.5}
              borderRadius="xl"
              mt={2}
            >
              <SegmentedControl
                value={isYearly ? "yearly" : "monthly"}
                onValueChange={(details) =>
                  setIsYearly(details.value === "yearly")
                }
                items={[
                  { label: t("monthly"), value: "monthly" },
                  {
                    label: `${t("yearly")} 🎁`,
                    value: "yearly",
                  },
                ]}
                size="sm"
              />
            </HStack>

            {isYearly && (
              <Text fontSize="sm" color="primary.500" fontWeight="semibold">
                ✨ {t("yearly-save")}
              </Text>
            )}
          </VStack>

          {/* Pricing Cards */}
          {isLoading ? (
            <Flex justify="center" py={20}>
              <Spinner size="lg" color="primary.500" />
            </Flex>
          ) : (
            <SimpleGrid
              columns={{ base: 1, md: 3 }}
              gap={{ base: 6, md: 8 }}
              maxW="5xl"
              mx="auto"
            >
              {enrichedPlans.map((plan) => (
                <PricingCard
                  key={plan.id}
                  plan={plan}
                  isCurrentPlan={currentPlan === plan.id}
                  isYearly={isYearly}
                  onSelect={handlePlanSelect}
                  isLoading={
                    checkoutLoading && selectedCheckoutPlan === plan.id
                  }
                />
              ))}
            </SimpleGrid>
          )}

          {/* FAQ Section */}
          <Box maxW="3xl" mx="auto" mt={{ base: 16, md: 24 }}>
            <VStack gap={2} textAlign="center" mb={8}>
              <HStack gap={2} color="primary.500">
                <LuMessageCircleQuestion size={24} />
                <Heading as="h2" size="lg" fontWeight="bold">
                  {t("faq-title")}
                </Heading>
              </HStack>
            </VStack>

            <VStack gap={4} align="stretch">
              {faqItems.map((item, idx) => (
                <FaqItem key={idx} question={item.q} answer={item.a} />
              ))}
            </VStack>
          </Box>
        </Box>
      </SlideUp>

      <LoginModal
        open={loginModalOpen}
        onOpenChange={setLoginModalOpen}
        initialMode="login"
      />
    </>
  );
}

// ────────────────────────────────────────────
// Internal helpers
// ────────────────────────────────────────────

function getFeatureKeysForPlan(
  planKey: "free" | "plus" | "premium",
  limits: { maxAnalyses: number; maxCoupons: number },
): string[] {
  const analysisLabel =
    limits.maxAnalyses >= 999
      ? "unlimited-daily-analyses"
      : `${limits.maxAnalyses} daily-analyses`;
  const couponLabel =
    limits.maxCoupons >= 999
      ? "unlimited-daily-coupons"
      : `${limits.maxCoupons} daily-coupons`;

  const base = [analysisLabel, couponLabel, "basic-analysis"];

  if (planKey === "plus") {
    return [...base, "detailed-analysis", "h2h-comparison", "coupon-builder"];
  }

  if (planKey === "premium") {
    return [
      ...base,
      "detailed-analysis",
      "h2h-comparison",
      "coupon-builder",
      "spor-toto",
      "ad-free",
      "priority-support",
    ];
  }

  return base;
}

/** Collapsible FAQ item */
function FaqItem({ question, answer }: { question: string; answer: string }) {
  const [open, setOpen] = useState(false);
  const cardBg = useColorModeValue("white", "gray.900");

  return (
    <Card.Root
      bg={cardBg}
      borderRadius="xl"
      cursor="pointer"
      transition="all 0.2s"
      _hover={{ shadow: "md" }}
      onClick={() => setOpen((prev) => !prev)}
    >
      <Card.Body p={5}>
        <Flex justify="space-between" align="center">
          <Text fontWeight="semibold" fontSize="sm">
            {question}
          </Text>
          <Box
            transform={open ? "rotate(180deg)" : "rotate(0deg)"}
            transition="transform 0.2s"
            flexShrink={0}
            ml={3}
          >
            <LuChevronDown size={18} />
          </Box>
        </Flex>
        {open && (
          <Text mt={3} fontSize="sm" color="fg.muted" lineHeight="1.7">
            {answer}
          </Text>
        )}
      </Card.Body>
    </Card.Root>
  );
}
