import { api } from '@/services/api';
import { useEffect, useRef, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
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 timerRef = useRef<NodeJS.Timeout | null>(null);

  // Poll task result
  const pollTaskResult = async (taskId: string) => {
    try {
      let attempts = 0;
      const maxAttempts = 30 * 20; // Maximum polling for 10 minutes

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

        // Check task status, continue polling only when in progress
        if (result.status === 'completed') {
          // Task completed, stop polling
          return;
        } else if (result.status === 'failed') {
          // Task failed, stop polling and set error
          setError('Task execution failed');
          return;
        } else if (
          result.status === 'running' ||
          result.status === 'pending' ||
          result.status === 'pending_audit' ||
          result.status === 'processing'
        ) {
          // Task still in progress, continue polling
          if (attempts < maxAttempts) {
            timerRef.current = setTimeout(poll, 1000);
          } else {
            setError('Processing timeout');
          }
        } else {
          // Other status, stop polling
          return;
        }
      };

      poll();
    } catch (error) {
      console.error('Failed to poll task:', error);
      setError('Failed to get task information');
    }
  };

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

    if (paymentId) {
      setTaskId(paymentId);
      // Start polling
      pollTaskResult(paymentId);
    } else {
      alert('Missing taskId parameter');
      navigate(-1);
    }

    // Cleanup timer
    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} />;
  }

  // Default to generating status
  return <GeneratingComponent task={task} />;
};

export default ResultPage;
