import React, { useMemo, useEffect } from 'react';
import { useActivity } from '../context/ActivityContext';
import { MissionListViewProps } from '../types';
import MissionItemView from './MissionItemView';

const MissionListView = ({
  activityInfo,
  tabName,
  onMissionProgressUpdate,
  onCustomShare,
  onCustomTask,
  className = 'mission-list',
  style,
  loadingClassName = 'loading',
  errorClassName = 'error',
  emptyClassName = 'empty',
  itemsClassName = 'mission-items',
  loadingText = '加载任务中...',
  errorText = '加载失败',
  emptyText = '暂无任务',
  isShowStepMission = false,
}: MissionListViewProps): React.ReactElement => {
  const { missions, loading, error, refreshActivity } = useActivity();
  // 监听页面可见性变化
  useEffect(() => {
    const handleVisibilityChange = () => {
      // 当页面变为可见时刷新数据
      if (document.visibilityState === 'visible') {
        console.log('页面变为可见，刷新任务数据');
        refreshActivity(true); // 使用静默刷新，避免显示loading状态
      }
    };

    // 添加事件监听器
    document.addEventListener('visibilitychange', handleVisibilityChange);

    // 清理函数：组件卸载时移除事件监听器
    return () => {
      document.removeEventListener('visibilitychange', handleVisibilityChange);
    };
  }, [refreshActivity]);

  const filteredMissions = useMemo(() => {
    if (!tabName) return missions;
    if (isShowStepMission) {
      return missions.filter(mission => mission.tabName === tabName);
    }
    console.log('missions', missions.filter(mission => mission.tabName === tabName && mission.info?.stepMissionFlag !== true));
    return missions.filter(mission => mission.tabName === tabName && mission.info?.stepMissionFlag !== true);
  }, [missions, tabName]);

  if (loading) {
    return (
      <div
        className={`${className} ${loadingClassName}`}
        style={style}
      >
        {loadingText}
      </div>
    );
  }

  if (error) {
    return (
      <div
        className={`${className} ${errorClassName}`}
        style={style}
      >
        {errorText}: {error}
      </div>
    );
  }

  if (filteredMissions.length === 0) {
    return (
      <div
        className={`${className} ${emptyClassName}`}
        style={style}
      >
        {emptyText}
      </div>
    );
  }

  return (
    <div className={className} style={style}>
      <div
        className={itemsClassName}>
        {filteredMissions.map((mission, index) => (
          // 如果 mission.info?.stepMissionFlag 为 true，则不显示 且配置了不显示阶段任务
          mission.info?.stepMissionFlag !== true && isShowStepMission === false && (
            <MissionItemView
              key={index}
              activityInfo={activityInfo}
              mission={mission}
              onProgressUpdate={onMissionProgressUpdate}
              onCustomShare={onCustomShare}
              onCustomTask={onCustomTask}
            />
          )
        ))}
      </div>
    </div>
  );
};

export default MissionListView;