import React, { useState, useEffect, useRef } from 'react';
import lottie from 'lottie-web';
import './index.css';

// 状态动画映射
const statusAnimationMap = {
  'HR初筛未通过': () => import('@/assets/animations/interviewStatus/1-off_初筛未通过.json'),
  'HR评估中': () => import('@/assets/animations/interviewStatus/1-on_hr评估中.json'),
  '面试未通过': () => import('@/assets/animations/interviewStatus/2-off_面试未通过.json'),
  '到场面试': () => import('@/assets/animations/interviewStatus/2-on_到场面试.json'),
  '收到通知': () => import('@/assets/animations/interviewStatus/2-on_收到通知.json'),
  '等待面试': () => import('@/assets/animations/interviewStatus/2-wati_等待面试.json'),
  '未参与面试': () => import('@/assets/animations/interviewStatus/3-off_未参与面试.json'),
  '等待HR通知': () => import('@/assets/animations/interviewStatus/3-wati_等待HR通知.json'),
  '拒绝Offer': () => import('@/assets/animations/interviewStatus/4-off_拒绝Offer.json'),
  '收到Offer': () => import('@/assets/animations/interviewStatus/4-on_收到Offer.json'),
  '等待回复': () => import('@/assets/animations/interviewStatus/4-wati_等待回复.json'),
};

export default ({ statusText, isOpen }) => {
  const animationContainer = useRef(null);
  const lottieInstance = useRef(null);
  const [animationData, setAnimationData] = useState(null);
  const [isVisible, setIsVisible] = useState(false);
  const [animationClass, setAnimationClass] = useState('');

  useEffect(() => {
    if (isOpen) {
      setIsVisible(true);
      setAnimationClass('expanding');
    } else if (isVisible) {
      setAnimationClass('collapsing');
      const timer = setTimeout(() => {
        setIsVisible(false);
        setAnimationClass('');
      }, 300); // 等待收起动画完成
      return () => clearTimeout(timer);
    }
  }, [isOpen, isVisible]);

  useEffect(() => {
    if (isOpen && statusText) {
      // 加载对应的动画数据
      const loadAnimation = statusAnimationMap[statusText];
      if (loadAnimation) {
        loadAnimation().then(module => {
          setAnimationData(module.default);
        });
      }
    }
  }, [isOpen, statusText]);

  useEffect(() => {
    if (animationData && animationContainer.current && isVisible) {
      // 清除之前的动画实例
      if (lottieInstance.current) {
        lottieInstance.current.destroy();
      }

      // 创建新的动画实例
      lottieInstance.current = lottie.loadAnimation({
        container: animationContainer.current,
        renderer: 'svg',
        loop: true,
        autoplay: true,
        animationData: animationData
      });

      return () => {
        if (lottieInstance.current) {
          lottieInstance.current.destroy();
        }
      };
    }
  }, [animationData, isVisible]);

  if (!isVisible) return null;

  return (
    <div className={`interview-status-animation-wrapper ${animationClass}`}>
      <div className="animation-container" ref={animationContainer} />
    </div>
  );
};