import React, { useState, useEffect, useRef } from 'react';
import classNames from 'classnames';
import styles from './index.less';
import { useGlobalModalServices } from '@/pages/GlobalModalServices/provider';
import { useMapState } from '../../MapStateContext';
import { 
  DATA_TYPE, 
  REGION_CODES,
  PANEL_ACTIVATION
} from '@/constants/dataTypes';
import { useLatestValue, useLatestValues } from '@/pages/Home_v_2504/hooks/useLatestValue';
// 导入区域树数据
import regionTreeResult from '../DistrictMapCustomized/regionTreeResult.json';
// 导入工具函数
import { processRegionTree } from '../../../config/commonUtils';

// 按钮数据类型定义
interface ButtonItem {
  key: string;
  label: string;
  hasChildren?: boolean;
  regionCode?: string;
  dataCode?: string;
  isDataTypeButton?: boolean; // 标记是否为数据类型按钮
  activatePanel?: 'left' | 'right'; // 标记该按钮激活哪个面板
}

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

interface AreaSelectorProps {}

const AreaSelector: React.FC<AreaSelectorProps> = () => {
  // 获取全局弹窗服务
  const { dispatch } = useGlobalModalServices();
  // 使用地图状态上下文
  const { mapState, updateRegion, updateDataType, setActivePanel } = useMapState();
  
  // 使用useLatestValues避免闭包问题
  const mapStateRef = useLatestValues(mapState);
  
  // 初始化按钮组数据的状态
  const [buttonGroupData, setButtonGroupData] = useState<ButtonGroupData>({
    level1: [
      { 
        key: 'chengdu', 
        label: '成都市', 
        hasChildren: true, 
        regionCode: REGION_CODES.CHENGDU,
        isDataTypeButton: false
      },
      { 
        key: 'oilSmoke', 
        label: '油烟事件', 
        dataCode: DATA_TYPE.RESTAURANT_OIL.OIL_SMOKE_EVENT,
        isDataTypeButton: true,
        activatePanel: 'right' // 油烟事件使用右侧面板时间
      },
      { 
        key: 'oilSmokeAlert', 
        label: '油烟告警', 
        dataCode: DATA_TYPE.RESTAURANT_OIL.OIL_SMOKE_ALERT,
        isDataTypeButton: true,
        activatePanel: 'left' // 油烟告警使用左侧面板时间
      },
      { 
        key: 'restaurant', 
        label: '餐饮企业', 
        dataCode: DATA_TYPE.RESTAURANT_OIL.RESTAURANT_FACILITY,
        isDataTypeButton: true,
        activatePanel: 'left' // 餐饮企业使用左侧面板时间
      },
    ],
    level2: {},
    level3: {},
  });

  // 状态管理
  const [activeLevel1, setActiveLevel1] = useState<string | null>(null);
  const [activeLevel2, setActiveLevel2] = useState<string | null>(null);
  const [activeLevel3, setActiveLevel3] = useState<string | null>(null);
  
  // 记录选中的区域信息
  const [selectedRegion, setSelectedRegion] = useState<{
    level1Key: string; 
    level1Label: string;
    level2Key: string | null; 
    level2Label: string | null;
    level3Key: string | null;
    level3Label: string | null;
    regionCode: string;
  }>({
    level1Key: 'chengdu',
    level1Label: '成都市',
    level2Key: null,
    level2Label: null,
    level3Key: null,
    level3Label: null,
    regionCode: REGION_CODES.CHENGDU
  });
  
  // 激活的数据类型按钮键
  const [activeDataTypeKey, setActiveDataTypeKey] = useState<string>('oilSmoke');
  
  // 悬停状态管理
  const [hoverLevel1, setHoverLevel1] = useState<string | null>(null);
  const [hoverLevel2, setHoverLevel2] = useState<string | null>(null);
  
  // 悬停计时器
  const hoverTimerRef = useRef<any>(null);
  
  // 控制菜单组是否展开
  const [menuExpanded, setMenuExpanded] = useState(false);
  
  // 控制第二层、第三层按钮组的显示
  // 使用 hover 或 active 状态来控制显示，但也要考虑整体菜单是否展开
  const showLevel2 = menuExpanded && (hoverLevel1 || activeLevel1) && 
    buttonGroupData.level2[hoverLevel1 || activeLevel1 || ''];
  const showLevel3 = menuExpanded && (hoverLevel2 || activeLevel2) && 
    buttonGroupData.level3[hoverLevel2 || activeLevel2 || ''];

  // 根据数据类型找到对应的按钮键
  const findDataTypeButtonKey = (dataCode: string): string | null => {
    const dataTypeButton = buttonGroupData.level1.find(
      button => button.isDataTypeButton && button.dataCode === dataCode
    );
    return dataTypeButton ? dataTypeButton.key : null;
  };

  // 根据数据类型找到对应的按钮
  const findDataTypeButton = (dataCode: string): ButtonItem | null => {
    return buttonGroupData.level1.find(
      button => button.isDataTypeButton && button.dataCode === dataCode
    ) || null;
  };

  // 初始化时从 JSON 加载区域树数据
  useEffect(() => {
    if (!regionTreeResult?.data) return;
    
    try {
      // 使用公共工具函数处理区域树数据
      const processedData = processRegionTree(regionTreeResult.data);
      
      // 使用解析后的数据更新按钮组
      setButtonGroupData(prevData => ({
        ...prevData,
        level2: {
          chengdu: processedData.level2
        },
        level3: processedData.level3
      }));
    } catch (error) {
      console.error('处理区域树数据出错:', error);
    }
  }, []);

  // 初始化时设置默认选中的数据类型按钮
  useEffect(() => {
    // 等待按钮组数据加载完成
    if (buttonGroupData.level1.length === 0) return;
    
    const currentDataCode = mapStateRef.current.dataCode;
    const buttonKey = findDataTypeButtonKey(currentDataCode);
    
    if (buttonKey) {
      setActiveDataTypeKey(buttonKey);
      
      // 同时设置正确的激活面板
      const button = findDataTypeButton(currentDataCode);
      if (button && button.activatePanel) {
        setActivePanel(button.activatePanel);
      }
    } else {
      // 如果找不到匹配的按钮，默认选中油烟事件
      setActiveDataTypeKey('oilSmoke');
      // 并更新数据类型和激活面板
      const defaultDataCode = DATA_TYPE.RESTAURANT_OIL.OIL_SMOKE_EVENT;
      if (mapStateRef.current.dataCode !== defaultDataCode) {
        updateDataType(defaultDataCode);
        setActivePanel('right'); // 油烟事件默认使用右侧面板
      }
    }
  }, [buttonGroupData.level1]);

  // 监听地图数据类型变化
  useEffect(() => {
    const handleDataTypeChange = (event: CustomEvent) => {
      try {
        const newDataCode = event.detail?.dataCode;
        if (!newDataCode) return;
        
        const buttonKey = findDataTypeButtonKey(newDataCode);
        if (buttonKey && buttonKey !== activeDataTypeKey) {
          setActiveDataTypeKey(buttonKey);
          
          // 更新激活面板
          const button = findDataTypeButton(newDataCode);
          if (button && button.activatePanel) {
            setActivePanel(button.activatePanel);
          }
        }
      } catch (error) {
        console.error('处理数据类型变化事件出错:', error);
      }
    };
    
    window.addEventListener('mapDataTypeChange', handleDataTypeChange as EventListener);
    
    return () => {
      window.removeEventListener('mapDataTypeChange', handleDataTypeChange as EventListener);
    };
  }, [activeDataTypeKey]);

  // 根据区域代码查找对应的按钮信息
  const findButtonByRegionCode = (regionCode: string): {
    level1?: ButtonItem | null;
    level2?: ButtonItem | null;
    level3?: ButtonItem | null;
  } => {
    // 检查第一层
    const level1Button = buttonGroupData.level1.find(
      button => !button.isDataTypeButton && button.regionCode === regionCode
    ) || null;
    
    if (level1Button) {
      return { level1: level1Button };
    }
    
    // 检查第二层
    let level2Button: ButtonItem | null = null;
    let parentLevel2Key: string | null = null;
    
    for (const [parentKey, buttons] of Object.entries(buttonGroupData.level2)) {
      const found = buttons.find(button => button.regionCode === regionCode);
      if (found) {
        level2Button = found;
        parentLevel2Key = parentKey;
        break;
      }
    }
    
    if (level2Button) {
      const level1Button = buttonGroupData.level1.find(button => button.key === 'chengdu') || null;
      return { level1: level1Button, level2: level2Button };
    }
    
    // 检查第三层
    let level3Button: ButtonItem | null = null;
    let parentLevel3Key: string | null = null;
    
    for (const [parentKey, buttons] of Object.entries(buttonGroupData.level3)) {
      const found = buttons.find(button => button.regionCode === regionCode);
      if (found) {
        level3Button = found;
        parentLevel3Key = parentKey;
        break;
      }
    }
    
    if (level3Button && parentLevel3Key) {
      // 找到对应的二级按钮
      const level2Button = Object.values(buttonGroupData.level2)
        .flat()
        .find(button => button.key === parentLevel3Key) || null;
      
      const level1Button = buttonGroupData.level1.find(button => button.key === 'chengdu') || null;
      
      return { 
        level1: level1Button, 
        level2: level2Button, 
        level3: level3Button 
      };
    }
    
    return {};
  };
  
  // 更新选中的区域信息
  const updateSelectedRegion = (regionCode: string) => {
    const buttons = findButtonByRegionCode(regionCode);
    
    const newSelectedRegion = {
      level1Key: buttons.level1?.key || 'chengdu',
      level1Label: buttons.level1?.label || '成都市',
      level2Key: buttons.level2?.key || null,
      level2Label: buttons.level2?.label || null,
      level3Key: buttons.level3?.key || null,
      level3Label: buttons.level3?.label || null,
      regionCode: regionCode
    };
    
    setSelectedRegion(newSelectedRegion);
    
    // 同步激活状态
    setActiveLevel1('chengdu');
    setActiveLevel2(buttons.level2?.key || null);
    setActiveLevel3(buttons.level3?.key || null);
  };

  // 处理第一层行政区划按钮悬停
  const handleLevel1Hover = (key: string, hasChildren?: boolean) => {
    // 只处理行政区划按钮的悬停（成都市）
    if (key === 'chengdu' && hasChildren) {
      clearTimeout(hoverTimerRef.current);
      setHoverLevel1(key);
      setMenuExpanded(true);
      
      // 如果有选中的二级或三级，直接展开到对应级别
      if (selectedRegion.level3Key) {
        // 找到三级对应的二级父节点
        setHoverLevel2(selectedRegion.level2Key);
      }
    }
  };

  // 处理第二层行政区划按钮悬停
  const handleLevel2Hover = (key: string, hasChildren?: boolean) => {
    if (hasChildren) {
      clearTimeout(hoverTimerRef.current);
      setHoverLevel2(key);
    }
  };

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

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

  // 处理第一层按钮点击
  const handleLevel1Click = (key: string, hasChildren?: boolean, regionCode?: string, dataCode?: string, isDataTypeButton?: boolean) => {
    // 处理数据类型按钮 - 互斥关系
    if (isDataTypeButton) {
      // 只有在点击不同的数据类型按钮时才进行处理
      if (key !== activeDataTypeKey) {
        // 更新激活的数据类型按钮
        setActiveDataTypeKey(key);
        
        // 更新数据类型
        if (dataCode) {
          // 查找对应的按钮获取应该激活的面板
          const button = buttonGroupData.level1.find(b => b.key === key);
          const targetPanel = button?.activatePanel || 'right';
          
          console.log(`切换数据类型: ${dataCode}, 激活面板: ${targetPanel}`, {
            button,
            targetPanel
          });
          
          // 设置激活面板 - 由数据类型决定面板激活状态
          setActivePanel(targetPanel);
          
          // 获取最新的mapState
          const currentMapState = mapStateRef.current;
          
          // 确认面板的时间
          const currentTime = targetPanel === 'left' ? 
            currentMapState.leftPanelTime : 
            currentMapState.rightPanelTime;
              
          console.log(`切换数据类型: ${dataCode}, 使用${targetPanel}面板时间:`, {
            startTime: currentTime.startTime,
            endTime: currentTime.endTime,
            type: currentTime.type
          });
          
          // 调用更新数据类型，这会同时设置正确的gridType
          updateDataType(dataCode);
        }
      }
      return;
    }
    
    // 处理行政区划按钮点击 - 激活状态切换
    if (key === 'chengdu') {
      if (regionCode && regionCode !== selectedRegion.regionCode) {
        // 更新选中区域为成都市
        updateSelectedRegion(REGION_CODES.CHENGDU);
        // 更新地图区域展示
        updateRegion(REGION_CODES.CHENGDU);
      }
      
      // 切换菜单展开状态
      setMenuExpanded(!menuExpanded);
      return;
    }
  };

  // 处理第二层按钮点击
  const handleLevel2Click = (key: string, hasChildren?: boolean, regionCode?: string) => {
    if (!regionCode) return;

    // 更新选中的区域信息
    updateSelectedRegion(regionCode);
    
    // 更新地图区域展示
    updateRegion(regionCode);
    
    // 关闭菜单
    setMenuExpanded(false);
    setHoverLevel1(null);
    setHoverLevel2(null);
  };

  // 处理第三层按钮点击
  const handleLevel3Click = (key: string, regionCode?: string) => {
    if (!regionCode) return;
    
    // 更新选中的区域信息
    updateSelectedRegion(regionCode);
    
    // 更新地图区域展示
    updateRegion(regionCode);
    
    // 关闭菜单
    setMenuExpanded(false);
    setHoverLevel1(null);
    setHoverLevel2(null);
  };

  // 监听地图区域变化，同步选中状态
  useEffect(() => {
    const currentRegionCode = mapState.regionCode;
    if (currentRegionCode && currentRegionCode !== selectedRegion.regionCode) {
      updateSelectedRegion(currentRegionCode);
    }
  }, [mapState.regionCode]);

  // 默认展示成都市全貌
  useEffect(() => {
    // 初始化时设置成都市
    updateRegion(REGION_CODES.CHENGDU);
    
    // 初始化时设置默认数据类型为油烟事件
    const defaultDataCode = DATA_TYPE.RESTAURANT_OIL.OIL_SMOKE_EVENT;
    updateDataType(defaultDataCode);
    
    // 设置默认激活面板为右侧
    setActivePanel('right');
  }, []);

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

  // 显示的区域名称
  const displayRegionName = () => {
    if (selectedRegion.level3Label) {
      return selectedRegion.level3Label;
    } else if (selectedRegion.level2Label) {
      return selectedRegion.level2Label;
    } else {
      return '成都市';
    }
  };

  return (
    <div className={styles.areaSelector}>
      {/* 第一层按钮组 */}
      <div className={styles.level1ButtonGroup}>
        {buttonGroupData.level1.map((button) => {
          // 判断是否为行政区划按钮
          const isAdminButton = button.key === 'chengdu';
          
          // 判断按钮是否激活
          let isActive = false;
          
          if (button.isDataTypeButton) {
            // 数据类型按钮通过activeDataTypeKey判断激活状态
            isActive = activeDataTypeKey === button.key;
          } else {
            // 行政区划按钮始终显示当前选中的区域
            isActive = button.regionCode === mapState.regionCode || activeLevel1 === button.key;
          }
          
          return (
            <div 
              key={button.key}
              className={classNames(styles.button, {
                [styles.buttonActive]: isActive
              })}
              onClick={() => handleLevel1Click(
                button.key, 
                button.hasChildren, 
                button.regionCode, 
                button.dataCode,
                button.isDataTypeButton
              )}
              onMouseEnter={isAdminButton ? () => handleLevel1Hover(button.key, button.hasChildren) : undefined}
              onMouseLeave={isAdminButton ? handleMouseLeave : undefined}
            >
              {isAdminButton ? displayRegionName() : button.label}
              {isAdminButton && (
                <img 
                  src={require('@/assets/images/V-2504/map-district-arrow.png')} 
                  className={styles.arrow}
                  alt=""
                />
              )}
            </div>
          );
        })}
      </div>

      {/* 第二层按钮组 */}
      {showLevel2 && (
        <div 
          className={styles.level2ButtonGroup}
          onMouseEnter={handleSubMenuMouseEnter}
          onMouseLeave={handleMouseLeave}
        >
          {buttonGroupData.level2[hoverLevel1 || activeLevel1 || ''].map((button) => (
            <div 
              key={button.key}
              className={classNames(styles.button, {
                [styles.buttonActive]: selectedRegion.level2Key === button.key || button.regionCode === mapState.regionCode
              })}
              onClick={() => handleLevel2Click(button.key, button.hasChildren, button.regionCode)}
              onMouseEnter={button.hasChildren ? () => handleLevel2Hover(button.key, button.hasChildren) : undefined}
            >
              {button.label}
            </div>
          ))}
        </div>
      )}

      {/* 第三层按钮组 */}
      {showLevel3 && (
        <div 
          className={styles.level3ButtonGroup}
          onMouseEnter={handleSubMenuMouseEnter}
          onMouseLeave={handleMouseLeave}
        >
          {buttonGroupData.level3[hoverLevel2 || activeLevel2 || ''].map((button) => (
            <div 
              key={button.key}
              className={classNames(styles.button, {
                [styles.buttonActive]: selectedRegion.level3Key === button.key || button.regionCode === mapState.regionCode
              })}
              onClick={() => handleLevel3Click(button.key, button.regionCode)}
            >
              {button.label}
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

export default AreaSelector; 