
import React, { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';

interface LoadingSectionProps {
  onComplete?: () => void;
  isComplete?: boolean;
}

const LoadingSection: React.FC<LoadingSectionProps> = ({ onComplete, isComplete }) => {
  const { t } = useTranslation();
  const [progress, setProgress] = useState(0);
  const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);

  useEffect(() => {
    intervalRef.current = setInterval(() => {
      setProgress(prev => {
        if (prev >= 100) {
          if (intervalRef.current) clearInterval(intervalRef.current);
          return 100;
        }
        const increment = prev < 70 ? 0.5 : prev < 90 ? 0.2 : 0.1;
        return Math.min(prev + increment, 100);
      });
    }, 100);
    return () => {
      if (intervalRef.current) clearInterval(intervalRef.current);
    };
  }, []);

  useEffect(() => {
    if (!isComplete) return;
    if (intervalRef.current) clearInterval(intervalRef.current);
    setProgress(100);
    const timer = setTimeout(() => {
      onComplete?.();
    }, 400);
    return () => clearTimeout(timer);
  }, [isComplete]);

  const getStepMessage = (p: number) => {
    if (p < 30) return t('analysis.loadingStep1');
    if (p < 50) return t('analysis.loadingStep2');
    if (p < 80) return t('analysis.loadingStep3');
    return t('analysis.loadingStep4');
  };

  return (
    <div className="loading-container">
      <div className="loading-content">
        {/* Logo */}
        <div className="loading-logo">
          <img src="/assets/images/ADO2_with Slogan_white.svg" alt="ADO2" />
        </div>

        {/* Loading Spinner and Text */}
        <div className="loading-section">
          <h2 className="loading-title">{t('analysis.loadingTitle')}</h2>

          <div className="loading-spinner-wrapper">
            <img
              src="/assets/images/loading-spinner.svg"
              alt="Loading"
              className="loading-spinner-icon"
            />
          </div>

          <div className="loading-progress-wrapper">
            <div className="loading-progress-bar">
              <div
                className="loading-progress-fill"
                style={{ width: `${progress}%` }}
              />
            </div>
            <span className="loading-progress-text">{Math.floor(progress)}%</span>
          </div>
          <p className="loading-step-message">{getStepMessage(progress)}</p>
        </div>
      </div>
    </div>
  );
};

export default LoadingSection;
