import Tabs from '@/components/Tabs';
import React, { useMemo, useEffect, useRef } from 'react';
import DistrictMap from './DistrictMap';
import EmphasisAreaMap from './EmphasisAreaMap';
import MapNotification from './MapNotification';
import NavigationBar from './NavigationBar';
import AreaSelector from './AreaSelector';
import VideoSelector from './VideoSelector';
import { useDashboard } from '../context';
import { useMapState } from '../MapStateContext';
import { INDUSTRY_PAGE_IDS } from '@/constants/dataTypes';
import styles from './index.less';
import DistrictMapCustomized from './DistrictMapCustomized';
// import CooglMapDemo from './CooglMapDemo';

// 修改地图组件的属性类型
interface MapComponentProps {
  onMapInstanceChange?: (instance: any) => void;
}

// 扩展地图组件类型，添加属性
const Map: Record<string, React.FC<MapComponentProps>> = {
  // '1': CooglMapDemo,
  '1': DistrictMapCustomized,
  // '1': DistrictMap,
  '2': EmphasisAreaMap,
};
// const MapContainer: React.FC = () => {
//   return (
//     <div className={styles.container}>
//       {/* 地图区域 - 后续实现 */}
//       <div className={styles.mapControls}>
//         <div className={styles.tabItem + ' ' + styles.active}>桥梁分布</div>
//         <div className={styles.tabItem}>道路分布</div>
//         <div className={styles.tabItem}>桥梁位置分布</div>
//       </div>
//       <div className={styles.mapPlaceholder}>
//         {/* 地图将在未来实现 */}
//         <span>地图区域 - 后续实现</span>
//       </div>
//     </div>
//   );
// };

// 简单的防抖函数
const debounce = (fn: Function, delay: number) => {
  let timer: number | null = null;
  return (...args: any[]) => {
    if (timer) {
      clearTimeout(timer);
    }
    timer = window.setTimeout(() => {
      fn(...args);
      timer = null;
    }, delay);
  };
};

const MapContainer = () => {
  const [topKey, setTopKey] = React.useState('1');
  const { activePage } = useDashboard();
  const isHomePage = activePage === 'home';
  const { mapState, setMapInstance } = useMapState();
  const lastEventRef = useRef<string>('');
  
  // 处理地图实例变化
  const handleMapInstanceChange = (instance: any) => {
    console.log('*/*/*/Map instance updated:', instance);
    if (instance && instance.params) {
      console.log('MapContainer收到有效地图实例，传递给MapStateContext');
      setMapInstance(instance);
    } else {
      console.warn('MapContainer收到无效地图实例');
    }
  };

  // 监听页面上的 DateSelector 组件时间变化 - 由 MapStateContext 处理
  useEffect(() => {
    // 使用防抖处理事件，避免短时间内多次触发
    const debouncedHandleChange = debounce((event: CustomEvent) => {
      // 检查是否重复事件
      const eventStr = JSON.stringify(event.detail);
      if (eventStr === lastEventRef.current) {
        console.log('忽略重复的日期变更事件');
        return;
      }
      
      // 更新最后处理的事件
      lastEventRef.current = eventStr;
      console.log('接收到日期变更事件，已由 MapStateContext 处理');
    }, 300);
    
    const handleDateChange = (event: CustomEvent) => {
      debouncedHandleChange(event);
    };
    
    window.addEventListener('mapDateChange', handleDateChange as EventListener);
    
    return () => {
      window.removeEventListener('mapDateChange', handleDateChange as EventListener);
    };
  }, []);
  
  // 监听数据类型变化 - 由 MapStateContext 处理
  // useEffect(() => {
  //   const handleDataTypeChange = (event: CustomEvent) => {
  //     // 所有逻辑已移至 MapStateContext
  //     // console.log('接收到数据类型变更事件，已由 MapStateContext 处理');
  //   };
    
  //   window.addEventListener('mapDataTypeChange', handleDataTypeChange as EventListener);
    
  //   return () => {
  //     window.removeEventListener('mapDataTypeChange', handleDataTypeChange as EventListener);
  //   };
  // }, []);

  // 判断当前是否为视频页面
  const isVideoPage = useMemo(() => {
    return activePage === INDUSTRY_PAGE_IDS.VIDEO_KEY_AREAS ||
           activePage === INDUSTRY_PAGE_IDS.VIDEO_BACK_STREETS ||
           activePage === INDUSTRY_PAGE_IDS.VIDEO_FARMERS_MARKET ||
           activePage === INDUSTRY_PAGE_IDS.VIDEO_SUBWAY_ENTRANCES;
  }, [activePage]);

  const renderMap = useMemo(() => {
    const MapComponent = Map[topKey];
    // 传递 onMapInstanceChange 回调给地图组件
    return <MapComponent onMapInstanceChange={handleMapInstanceChange} />;
  }, [topKey]);

  return (
    <div className={styles.container}>
      <div className={styles.topTabsWarp}>
        {/* <Tabs
          defaultValue="1"
          items={[
            { key: '1', label: '区（市）县' },
            { key: '2', label: '重点区域' },
          ]}
          onChange={(e) => {
            setTopKey(e);
          }}
        /> */}
      </div>
      
      {/* 地图上的最新事件和区域选择 */}
      <MapNotification />
      
      {/* 根据页面类型显示不同的选择器 */}
      {!isHomePage && (
        isVideoPage ? <VideoSelector /> : <AreaSelector />
      )}
      
      {/* 只在下钻页面显示导航栏 */}
      {!isHomePage && <NavigationBar />}
      
      <div className={styles.mapContent}>{renderMap}</div>
    </div>
  );
};

export default MapContainer;