'use client';

import { Button, IconButton } from '@/components/ui/button';
import { Drawer, DrawerContent, DrawerHeader, DrawerTitle } from '@/components/ui/drawer';
import { useState, useMemo } from 'react';
import SubscribeProducts from './SubscribeProducs';
import SubscribeProductsSkeleton from './SubscribeProductsSkeleton';
import CarouselBanner from './CarouselBanner';
import { useGetSubProductCheckoutLink, useGetSubProductList } from '@/hooks/useWallet';
import { SubProductListOutput, Period, VipType } from '@/services/wallet/types';
import { useAtom } from 'jotai';
import QueryString from 'qs';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';

function SubscribeBackground() {
  return (
    <div
      className="absolute top-0 right-0 bottom-0 left-0"
      style={{
        backgroundImage: "url('/images/vip/drawer-bg.png')",
        backgroundSize: 'contain',
        backgroundPosition: 'top center',
        backgroundRepeat: 'no-repeat',
      }}
    ></div>
  );
}

// 数据转换函数
const convertProductListToPricingPlans = (productList: SubProductListOutput[]) => {
  if (!productList) return [];

  return productList.map((product, index) => {
    // 根据订阅时长获取标题
    const getTitleByPeriod = (period?: Period) => {
      switch (period) {
        case Period.SubMonth:
          return '1 Month';
        case Period.SubSeason:
          return '3 Months';
        case Period.SubYear:
          return '12 Months';
        default:
          return 'Unknown';
      }
    };

    // 计算月单价（如果不是月订阅）
    const getSubtitle = (period?: Period, payAmount?: number) => {
      if (!payAmount) return '';

      const monthlyPrice = payAmount / 100; // 转换为元

      switch (period) {
        case Period.SubSeason:
          return `$${(monthlyPrice / 3).toFixed(2)}/Month`;
        case Period.SubYear:
          return `$${(monthlyPrice / 12).toFixed(2)}/Month`;
        default:
          return '';
      }
    };

    return {
      id: index + 1, // 使用索引+1作为ID
      title: getTitleByPeriod(product.period),
      subtitle: getSubtitle(product.period, product.payAmount),
      price: product.payAmount ? (product.payAmount / 100).toFixed(2) : '0.00', // 转换为元并格式化
      discount: product.discount || '',
      isSelected: false, // 初始都不选中
      productId: product.productId, // 保留原始产品ID用于后续操作
    };
  });
};

const SubscribeVipDrawer = () => {
  const [selectedPlan, setSelectedPlan] = useState<number>(0); // 默认不选择任何计划
  // const [isVipDrawerOpen, setIsVipDrawerOpen] = useAtom(isVipDrawerOpenAtom)
  const [isVipDrawerOpen, setIsVipDrawerOpen] = useState({
    open: false,
    vipType: undefined,
  });

  const { data: productList, isLoading } = useGetSubProductList();
  const { mutateAsync, isPending } = useGetSubProductCheckoutLink();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  // 转换产品数据为组件需要的格式
  const pricingPlans = useMemo(() => {
    const plans = convertProductListToPricingPlans(productList || []);
    // 设置选中状态
    return plans.map((plan) => ({
      ...plan,
      isSelected: plan.id === selectedPlan,
    }));
  }, [productList, selectedPlan]);

  // 设置默认选中第二个计划（3个月）
  useMemo(() => {
    if (pricingPlans.length > 0 && selectedPlan === 0) {
      const seasonPlan = pricingPlans.find((plan) => plan.title === '3 Month');
      if (seasonPlan) {
        setSelectedPlan(seasonPlan.id);
      } else {
        setSelectedPlan(pricingPlans[0].id); // 如果没有3个月计划，选择第一个
      }
    }
  }, [pricingPlans, selectedPlan]);

  const handleClose = () => {
    setIsVipDrawerOpen({ open: false, vipType: undefined });
  };

  const handleSubscribe = async () => {
    // 获取选中的计划详情
    const selectedPlanData = pricingPlans.find((plan) => plan.id === selectedPlan);
    if (selectedPlanData && selectedPlanData.productId) {
      // 这里可以调用订阅API，使用selectedPlanData.productId

      const query = {
        ...QueryString.parse(searchParams.toString()),
        back: 1,
      };

      const baseURL = `${process.env.NEXT_PUBLIC_APP_URL}${pathname}?${QueryString.stringify(query)}`;

      const response = await mutateAsync({
        subProductId: selectedPlanData.productId,
        returnUrl: baseURL,
        cancelUrl: baseURL,
      });
      const { payUrl } = response || {};
      if (payUrl) {
        window.location.href = payUrl;
      }
    }
  };

  return (
    <Drawer
      open={isVipDrawerOpen.open}
      onOpenChange={(val) => setIsVipDrawerOpen({ open: val, vipType: isVipDrawerOpen.vipType })}
      direction="right"
    >
      <DrawerContent className="min-h-screen">
        <SubscribeBackground />
        <div className="relative">
          <DrawerHeader className="flex items-center gap-2 p-6">
            <IconButton
              iconfont="icon-arrow-right"
              variant="ghost"
              size="small"
              onClick={handleClose}
            />
            <DrawerTitle className="txt-title-m text-txt-primary-normal">
              CrushLevel Vip
            </DrawerTitle>
          </DrawerHeader>
        </div>

        <div className="relative flex-1 overflow-y-auto">
          <div className="relative box-border flex size-full flex-col content-stretch items-center justify-start gap-6 pb-20">
            {/* 顶部横幅区域 */}
            <CarouselBanner vipType={isVipDrawerOpen.vipType} visible={isVipDrawerOpen.open} />

            {/* 价格选择卡片 */}
            {isLoading ? (
              <SubscribeProductsSkeleton />
            ) : (
              <SubscribeProducts pricingPlans={pricingPlans} setSelectedPlan={setSelectedPlan} />
            )}
          </div>
        </div>

        <div className="relative p-6">
          <Button block variant="vip" size="large" onClick={handleSubscribe} loading={isPending}>
            <i className="iconfont icon-icon-vip !text-[24px] leading-none" />
            Subscribe
          </Button>
        </div>
      </DrawerContent>
    </Drawer>
  );
};

export default SubscribeVipDrawer;
