import React, { useState, useEffect, useRef } from 'react';
import classNames from 'classnames';
import styles from './index.less';
import { useMapState } from '../../MapStateContext';
import { useDashboard } from '../../context';
import { REGION_CODES, INDUSTRY_PAGE_IDS } from '@/constants/dataTypes';
import PanelTitle from '@/pages/Home_v_2504/components/common/PanelTitle';
import regionTreeResult from '../DistrictMapCustomized/regionTreeResult.json';
import { useGlobalModalServices } from '@/pages/GlobalModalServices/provider';

// 按钮数据类型定义
interface ButtonItem {
  key: string;
  label: string;
  hasChildren?: boolean;
  regionCode?: string;
  lineCode?: string;
}

// 定义按钮组数据类型
interface ButtonGroupData {
  level1: ButtonItem[];
  level2: Record<string, ButtonItem[]>;
}

// 模拟地铁站点数据
const subwayStationsData: Record<string, string[]> = {
  'line1': ['科学城站', '广都站', '龙泉驿站', '龙泉广场站', '书房站', '界牌站', '苏码头站', '东光站'],
  'line2': ['犀浦站', '天河路站', '百草路站', '金周路站', '迎宾大道站', '茶店子站', '人民北路站', '人民公园站'],
  'line3': ['钟楼站', '市二医院站', '春熙路站', '新南门站', '磨子桥站', '华西坝站', '省体育馆站', '衣冠庙站'],
  'line4': ['西河站', '清江站', '文化宫站', '西南财大站', '太平园站', '迎晖路站', '琉璃场站', '凤溪河站'],
  'line5': ['华阳站', '四河站', '华府大道站', '天府公园站', '华阳体育中心站', '锦城广场站', '川大锦城站', '天府五街站'],
  'line6': ['金融城站', '锦城湖站', '三岔站', '东山站', '万年场站', '理工大学站', '金融城东站', '德源站'],
  'line7': ['火车南站', '神仙树站', '高朋大道站', '太平园站', '驷马桥站', '火车北站', '九里堤站', '北站西二路站'],
  'line8': ['珠江路站', '凤凰大街站', '杉板桥站', '琉璃厂站', '春熙路站', '东大街站', '报春路站', '成渝立交站'],
  'line9': ['科学城站', '芳草街站', '锦城广场站', '世纪城站', '高新站', '金融城站', '天府三街站', '孵化园站'],
  'line10': ['太平寺站', '簇锦站', '武青南路站', '双流西站', '双流机场1航站楼站', '双流机场2航站楼站', '双华路站', '怡心湖站'],
};

const VideoSelector: React.FC = () => {
  // 使用地图状态上下文
  const { mapState, updateRegion } = useMapState();
  // 获取当前激活页面
  const { activePage } = useDashboard();
  // 获取弹窗服务
  const { dispatch } = useGlobalModalServices();
  
  // 按钮组数据状态
  const [buttonGroupData, setButtonGroupData] = useState<ButtonGroupData>({
    level1: [],
    level2: {},
  });

  // 状态管理
  const [activeLevel1, setActiveLevel1] = useState<string | null>(null);
  const [activeLevel2, setActiveLevel2] = useState<string | null>(null);
  
  // 记录选中的Level2按钮
  const [selectedLevel2Item, setSelectedLevel2Item] = useState<ButtonItem | null>(null);
  
  // 悬停状态管理
  const [hoverLevel1, setHoverLevel1] = useState<string | null>(null);
  
  // 悬停计时器
  const hoverTimerRef = useRef<any>(null);
  
  // 控制菜单组是否展开
  const [menuExpanded, setMenuExpanded] = useState(false);
  
  // 标题文本
  const [titleText, setTitleText] = useState('区域选择');

  // 地铁线路选择状态
  const [selectedLineCode, setSelectedLineCode] = useState<string>('');

  // 记录原始标签文本
  const originalLabelsRef = useRef<Record<string, string>>({});

  // 设置区县级数据
  const initializeDistrictData = () => {
    if (!regionTreeResult?.data) return;
    
    try {
      // 处理区域树数据 - 只获取到区县级别（不包含街道）
      const chengduData = regionTreeResult.data[0];
      if (!chengduData || !chengduData.children) return;
      
      const districts = chengduData.children.map(district => ({
        key: district.id.toString(),
        label: district.gridName,
        regionCode: district.id.toString(),
      }));

      console.log('成都市区县数据:', districts);
      
      return {
        chengduKey: {
          key: 'chengdu',
          label: '成都市',
          regionCode: REGION_CODES.CHENGDU,
          hasChildren: true,
        },
        districts,
      };
    } catch (error) {
      console.error('处理区域树数据出错:', error);
      return null;
    }
  };

  // 根据页面类型初始化按钮组数据
  useEffect(() => {
    const districtData = initializeDistrictData();
    
    if (activePage === INDUSTRY_PAGE_IDS.VIDEO_KEY_AREAS) {
      // 重点区域页面
      setTitleText('重点区域');
      const level1Buttons = [
        { key: 'area', label: '区域选择', hasChildren: true },
      ];
      
      // 存储原始标签文本
      level1Buttons.forEach(btn => {
        originalLabelsRef.current[btn.key] = btn.label;
      });
      
      setButtonGroupData({
        level1: level1Buttons,
        level2: {
          'area': [
            { key: 'sichuan', label: '四川省人民政府' },
            { key: 'chengdu', label: '成都市人民政府' },
            { key: 'cgw', label: '成都市城管委' },
          ]
        },
      });
    } 
    else if (activePage === INDUSTRY_PAGE_IDS.VIDEO_SUBWAY_ENTRANCES) {
      // 地铁口页面
      setTitleText('地铁线路');
      const level1Buttons = [
        { key: 'line', label: '线路选择', hasChildren: true },
        { key: 'station', label: '站点选择', hasChildren: true },
      ];
      
      // 存储原始标签文本
      level1Buttons.forEach(btn => {
        originalLabelsRef.current[btn.key] = btn.label;
      });
      
      setButtonGroupData({
        level1: level1Buttons,
        level2: {
          'line': Array.from({ length: 10 }, (_, i) => ({
            key: `line${i + 1}`,
            label: `${i + 1}号线`,
            lineCode: `${i + 1}`,
          })),
          'station': []
        },
      });
    }
    else if (activePage === INDUSTRY_PAGE_IDS.VIDEO_FARMERS_MARKET || 
             activePage === INDUSTRY_PAGE_IDS.VIDEO_BACK_STREETS) {
      // 农贸市场或背街小巷页面
      const title = activePage === INDUSTRY_PAGE_IDS.VIDEO_FARMERS_MARKET ? '农贸市场' : '背街小巷';
      setTitleText(title);
      
      if (districtData) {
        const level1Buttons = [
          districtData.chengduKey,
        ];
        
        // 存储原始标签文本
        level1Buttons.forEach(btn => {
          originalLabelsRef.current[btn.key] = btn.label;
        });
        
        setButtonGroupData({
          level1: level1Buttons,
          level2: {
            'chengdu': districtData.districts
          },
        });
      }
    }
    
    // 重置选中状态
    setSelectedLevel2Item(null);
    setActiveLevel1(null);
    setActiveLevel2(null);
    
  }, [activePage]);

  // 根据选中的地铁线路更新站点数据
  useEffect(() => {
    if (selectedLineCode && activePage === INDUSTRY_PAGE_IDS.VIDEO_SUBWAY_ENTRANCES) {
      const lineKey = `line${selectedLineCode}`;
      const stationList = subwayStationsData[lineKey] || [];
      
      // 更新站点选择按钮组
      setButtonGroupData(prev => ({
        ...prev,
        level2: {
          ...prev.level2,
          'station': stationList.map((stationName, index) => ({
            key: `station_${index}`,
            label: stationName,
          }))
        }
      }));
    }
  }, [selectedLineCode, activePage]);

  // 控制第二层按钮组的显示
  const showLevel2 = menuExpanded && (hoverLevel1 || activeLevel1) && 
    buttonGroupData.level2[hoverLevel1 || activeLevel1 || ''];

  // 处理第一层按钮悬停
  const handleLevel1Hover = (key: string, hasChildren?: boolean) => {
    if (hasChildren) {
      clearTimeout(hoverTimerRef.current);
      setHoverLevel1(key);
      setMenuExpanded(true);
    }
  };

  // 处理鼠标离开
  const handleMouseLeave = () => {
    clearTimeout(hoverTimerRef.current);
    
    // 延迟关闭菜单，给用户一些时间移动到子菜单
    hoverTimerRef.current = setTimeout(() => {
      setHoverLevel1(null);
      setMenuExpanded(false);
    }, 300);
  };

  // 处理子菜单鼠标进入，取消清除悬停状态的计时器
  const handleSubMenuMouseEnter = () => {
    clearTimeout(hoverTimerRef.current);
  };

  // 打开视频弹窗
  const openVideoModal = (locationName: string, type: string) => {
    dispatch.push('VideoModal', {
      title: `${locationName || '监控'}视频`,
      props: {
        videoType: type,
        locationName: locationName,
      }
    });
  };

  // 处理第一层按钮点击
  const handleLevel1Click = (key: string, hasChildren?: boolean, regionCode?: string) => {
    // 如果按钮已经是激活状态，则点击后恢复默认状态
    if (activeLevel1 === key) {
      // 如果已选中了二级按钮，重置一级按钮的文本
      if (selectedLevel2Item && originalLabelsRef.current[key]) {
        // 找到当前按钮并更新标签
        setButtonGroupData(prev => {
          const updatedLevel1 = prev.level1.map(btn => {
            if (btn.key === key) {
              return { ...btn, label: originalLabelsRef.current[key] };
            }
            return btn;
          });
          return { ...prev, level1: updatedLevel1 };
        });
      }
      
      // 重置选中状态
      setSelectedLevel2Item(null);
      setActiveLevel1(null);
      setActiveLevel2(null);
      setMenuExpanded(false);
      return;
    }
    
    // 如果是区域按钮且有子菜单，切换菜单展开状态
    if (hasChildren) {
      setMenuExpanded(!menuExpanded);
      setActiveLevel1(key);
      return;
    }
    
    // 如果是成都市按钮，直接更新区域
    if (regionCode) {
      updateRegion(regionCode);
    }
    
    setActiveLevel1(key);
  };

  // 处理第二层按钮点击
  const handleLevel2Click = (key: string, level2Item: ButtonItem) => {
    // 设置选中状态
    setActiveLevel2(key);
    setSelectedLevel2Item(level2Item);
    
    // 获取当前一级按钮的key
    const level1Key = activeLevel1 || hoverLevel1;
    
    if (level1Key) {
      // 如果是地铁线路，特殊处理
      if (level2Item.lineCode) {
        // 更新"线路选择"按钮的标签为选中的线路名称
        setButtonGroupData(prev => {
          const updatedLevel1 = prev.level1.map(btn => {
            if (btn.key === 'line') {
              return { ...btn, label: level2Item.label };
            }
            return btn;
          });
          return { ...prev, level1: updatedLevel1 };
        });
        
        console.log('选择地铁线路:', level2Item.lineCode);
        setSelectedLineCode(level2Item.lineCode);
        
        // 选择线路后自动切换到站点选择
        setActiveLevel1('station');
        setMenuExpanded(true);
      } else {
        // 非地铁线路，正常更新当前按钮的标签
        setButtonGroupData(prev => {
          const updatedLevel1 = prev.level1.map(btn => {
            if (btn.key === level1Key) {
              return { ...btn, label: level2Item.label };
            }
            return btn;
          });
          return { ...prev, level1: updatedLevel1 };
        });
      }
    }
    
    // 如果是区域代码，更新地图区域
    if (level2Item.regionCode) {
      updateRegion(level2Item.regionCode);
    }
    
    // 打开视频弹窗
    const videoType = getVideoTypeFromPageId(activePage);
    if (videoType && !level2Item.lineCode) {
      openVideoModal(level2Item.label, videoType);
    }
    
    // 关闭菜单
    setMenuExpanded(false);
    setHoverLevel1(null);
  };

  // 从页面ID获取视频类型
  const getVideoTypeFromPageId = (pageId: string): string => {
    switch (pageId) {
      case INDUSTRY_PAGE_IDS.VIDEO_KEY_AREAS:
        return '3'; // 重点区域
      case INDUSTRY_PAGE_IDS.VIDEO_BACK_STREETS:
        return '2'; // 背街小巷
      case INDUSTRY_PAGE_IDS.VIDEO_FARMERS_MARKET:
        return '1'; // 农贸市场
      case INDUSTRY_PAGE_IDS.VIDEO_SUBWAY_ENTRANCES:
        return '4'; // 地铁口
      default:
        return '3';
    }
  };

  // 清除定时器
  useEffect(() => {
    return () => {
      clearTimeout(hoverTimerRef.current);
    };
  }, []);

  return (
    <div className={styles.videoSelector}>
      {/* 标题 */}
      <div className={styles.titleWrapper}>
        <PanelTitle title={titleText} />
      </div>
      
      <div className={styles.buttonGroup}>
        {/* 第一层按钮组 */}
        <div className={styles.level1ButtonGroup}>
            {buttonGroupData.level1.map((button) => (
            <div 
                key={button.key}
                className={classNames(styles.button, {
                [styles.buttonActive]: activeLevel1 === button.key || selectedLevel2Item !== null && button.label === selectedLevel2Item.label
                })}
                onClick={() => handleLevel1Click(button.key, button.hasChildren, button.regionCode)}
                onMouseEnter={() => handleLevel1Hover(button.key, button.hasChildren)}
                onMouseLeave={handleMouseLeave}
            >
                {button.label}
                {button.hasChildren && (
                <img 
                    src={require('@/assets/images/V-2504/map-district-arrow.png')} 
                    className={styles.arrow}
                    alt=""
                />
                )}
            </div>
            ))}
        </div>

        {/* 第二层按钮组 */}
        {showLevel2 && (
            <div 
            className={classNames(styles.level2ButtonGroup, {
              [styles.keyAreaLevel2]: activePage === INDUSTRY_PAGE_IDS.VIDEO_KEY_AREAS
            })}
            onMouseEnter={handleSubMenuMouseEnter}
            onMouseLeave={handleMouseLeave}
            >
            {buttonGroupData.level2[hoverLevel1 || activeLevel1 || '']?.map((button) => (
                <div 
                key={button.key}
                className={classNames(styles.button, {
                    [styles.buttonActive]: activeLevel2 === button.key
                })}
                onClick={() => handleLevel2Click(button.key, button)}
                >
                {button.label}
                </div>
            ))}
            </div>
        )}
      </div>
    </div>
  );
};

export default VideoSelector; 