import { getSubscription } from '@/services/user/portal';
import { useQuery } from '@tanstack/react-query';
import {
  Dialog,
  DialogContent,
  DialogTitle,
  DialogTrigger,
} from '@workspace/airo-ui/components/dialog';
import { useRef, useState } from 'react';

import TabContent from '@/components/SubscribePlan/PlanContent/index';
import PlanTabs from '@/components/SubscribePlan/PlanTabs/PlanTabs';
import { Button } from '@workspace/airo-ui/components/button';
import { useTranslations } from 'next-intl';

const OfferDialog = () => {
  const t = useTranslations('components.offerDialog');
  const tHome = useTranslations('components.home');

  const [open, setOpen] = useState(false);
  const [tabValue, setTabValue] = useState<'year' | 'month'>('year');
  const dialogRef = useRef<HTMLDivElement>(null);
  // 使用 useQuery 来管理请求
  const {
    data = [],
    isLoading,
    error,
    refetch,
  } = useQuery({
    queryKey: ['subscription'],
    queryFn: async () => {
      try {
        const response = await getSubscription({ skipErrorHandler: true });
        // 确保返回有效的数组，避免 undefined
        const list = response.data?.data?.list || [];
        return list.filter((v) => v.unit_time === 'Month') as API.Subscribe[];
      } catch (err) {
        // 自定义错误处理
        console.error('获取订阅数据失败:', err);
        // 返回空数组而不是抛出错误，避免 queryFn 返回 undefined
        return [] as API.Subscribe[];
      }
    },
    enabled: true, // 初始不执行，手动控制
    retry: 1, // 失败时重试1次
    refetchOnWindowFocus: true,
  });

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button className='mb-8 h-auto rounded-full border-[3px] border-white bg-white/10 px-8 py-2 text-lg font-bold text-white transition hover:bg-white/25 sm:px-6 sm:py-1.5'>
          {tHome('viewSubscriptionPlans')}
        </Button>
      </DialogTrigger>
      <DialogContent
        ref={dialogRef}
        className='rounded-0 h-full gap-0 px-4 py-8 sm:max-h-[95%] sm:!rounded-[32px] sm:px-8 sm:py-12 md:max-w-[1280px]'
      >
        <DialogTitle className={'sr-only'}></DialogTitle>
        <div className={'ml-6 sm:ml-0'}>
          <div className={'text-4xl font-bold text-[#0F2C53] md:mb-1 md:text-center'}>
            {t('selectPlan')}
          </div>
          <div className={'text-base font-medium text-[#666666] md:text-center'}>
            {t('selectYourPlan')}
          </div>
        </div>
        <div>
          <div className={'m-auto flex w-full sm:w-[362px]'}>
            <PlanTabs tabValue={tabValue} setTabValue={setTabValue} discount={20} />
          </div>
          <TabContent
            tabValue={tabValue}
            subscribeData={data}
            isLoading={isLoading}
            error={error}
            onRetry={refetch}
          />
        </div>
      </DialogContent>
    </Dialog>
  );
};

export default OfferDialog;
