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

import TabContent from '@/components/SubscribePlan/PlanContent/index';
import PlanTabs from '@/components/SubscribePlan/PlanTabs/PlanTabs';
import { useTranslations } from 'next-intl';

export interface OfferDialogRef {
  show: () => void;
  hide: () => void;
}

const OfferDialog = forwardRef<OfferDialogRef>((props, ref) => {
  const t = useTranslations('components.offerDialog');
  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次
  });

  useImperativeHandle(ref, () => ({
    show: () => {
      refetch();
      setOpen(true);
    },
    hide: () => setOpen(false),
  }));

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <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-full'
      >
        <DialogTitle className={'sr-only'}></DialogTitle>
        <div className={'ml-6 sm:ml-0'}>
          <div className={'text-4xl font-bold text-[#0F2C53] md:mb-4 md:text-center md:text-5xl'}>
            {t('selectPlan')}
          </div>
          <div className={'text-lg 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;
