import { useNavigate } from 'react-router-dom';
import { useEffect, useState } from 'react';

interface GeneratingComponentProps {
  task: any;
}

const GeneratingComponent: React.FC<GeneratingComponentProps> = ({ task }) => {
  const navigate = useNavigate();
  const [progress, setProgress] = useState(0);

  // Calculate real progress based on task creation time and type
  useEffect(() => {
    let interval: NodeJS.Timeout | null = null;

    const calculateProgress = () => {
      if (!task?.createdAt) return 0;

      const createdAt = new Date(task.createdAt).getTime();
      const now = Date.now();
      const elapsedMinutes = (now - createdAt) / (1000 * 60);

      // Determine estimated time based on task type
      const isVideo = task.taskType === 'video' || task.outputType === 'video' || task.type === 'video';
      const estimatedTime = isVideo ? 15 : 15; // Video 2.5 minutes, image 1 minute

      // Calculate progress percentage, maximum 95%
      const calculatedProgress = Math.min((elapsedMinutes / estimatedTime) * 100, 95);
      return Math.max(calculatedProgress, 0);
    };

    // Calculate immediately once
    setProgress(calculateProgress());

    // Update progress every second
    interval = setInterval(() => {
      setProgress(calculateProgress());
    }, 1000);

    return () => {
      if (interval) {
        clearInterval(interval);
      }
    };
  }, [task]);

  const handleLaterView = () => {
    navigate('/home', { replace: true });
  };

  console.log('task', task);

  return (
    <div className="result-page generating">
      <div className="generating-content">
        {/* Progress square */}
        <div className="progress-container">
          <div className="progress-circle">
            <div
              className="progress-fill"
              style={{
                background: `conic-gradient(#FFCF5F ${progress * 3.6}deg, transparent 0deg)`,
              }}
            />
            <div className="progress-inner">
              {/* Preview image or placeholder */}
              {task?.inputImages.length > 0 && task?.inputImages[0] ? (
                <img className="preview-image" src={task.inputImages[0]} alt="preview" />
              ) : (
                <div className="preview-placeholder">
                  <div className="placeholder-icon">🎨</div>
                </div>
              )}
              {/* Image overlay */}
              <div className="progress-overlay" />
              {/* Light scanning animation */}
              <div className="scan-light" />
              <div className="scan-progress">{Math.round(progress)}%</div>
            </div>
          </div>
        </div>

        {/* Status text */}
        <div className="status-section">
          <div className="status-title">
            <img className="status-icon-image" src="/assets/icons/funnel.png" alt="status" />
            <span className="status-title-text">Generating...</span>
          </div>
          <div className="status-subtitle">Content is being generated, please wait patiently</div>
        </div>

        {/* Action buttons */}
        <div className="generating-actions">
          <div className="later-btn" onClick={handleLaterView}>
            View Later
          </div>
        </div>

        {/* Tips information */}
        <div className="tips-section">
          <div className="tips-label">· T I P S ·</div>
          <div className="tips-text">Exiting this page does not affect generation progress</div>
        </div>
      </div>
    </div>
  );
};

export default GeneratingComponent;
