import { useEffect, useRef, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useServerSdk } from '../../hooks';
import ErrorComponent from './components/ErrorComponent';
import GeneratingComponent from './components/GeneratingComponent';
import SuccessComponent from './components/SuccessComponent';
import './index.css';

const ResultPage: React.FC = () => {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const [taskId, setTaskId] = useState<string | null>(null);
  const [task, setTask] = useState<any>(null);
  const [error, setError] = useState<string | null>(null);
  const serverSdk = useServerSdk();
  const timerRef = useRef<NodeJS.Timeout | null>(null);

  // 轮询任务结果
  const pollTaskResult = async (taskId: string) => {
    try {
      let attempts = 0;
      const maxAttempts = 30 * 20; // 最大轮询10分钟

      const poll = async () => {
        attempts++;
        const result = await serverSdk.getTaskProgress(taskId);
        setTask(result);

        // 检查任务状态，只有在进行中时才继续轮询
        if (result.status === 'completed') {
          // 任务完成，停止轮询
          return;
        } else if (result.status === 'failed') {
          // 任务失败，停止轮询并设置错误
          setError('任务执行失败');
          return;
        } else if (result.status === 'running' || result.status === 'pending' || result.status === 'pending_audit') {
          // 任务仍在进行中，继续轮询
          if (attempts < maxAttempts) {
            timerRef.current = setTimeout(poll, 1000);
          } else {
            setError('处理超时');
          }
        } else {
          // 其他状态，停止轮询
          return;
        }
      };

      poll();
    } catch (error) {
      console.error('轮询任务失败:', error);
      setError('获取任务信息失败');
    }
  };

  useEffect(() => {
    const paymentId = searchParams.get('paymentId') || searchParams.get('taskId');

    if (paymentId) {
      setTaskId(paymentId);
      // 开始轮询
      pollTaskResult(paymentId);
    } else {
      alert('缺少taskId参数');
      navigate(-1);
    }

    // 清理定时器
    return () => {
      if (timerRef.current) {
        clearTimeout(timerRef.current);
        timerRef.current = null;
      }
    };
  }, [searchParams, navigate]);

  if (!taskId) {
    return null;
  }

  if (error) {
    return <ErrorComponent error={error} />;
  }

  if (task?.status === 'completed' && task?.outputUrl) {
    return <SuccessComponent task={task} />;
  }

  // 默认显示生成中状态
  return <GeneratingComponent task={task} />;
};

export default ResultPage;
