import { useEffect, useRef, forwardRef, useImperativeHandle } from 'react';
import * as echarts from 'echarts';
import chinaGeoJSON from '../assets/china.json';
import type { MapItem } from '../types/data';

const geoNameMap: Record<string, string> = {
  '北京': '北京市', '天津': '天津市', '河北': '河北省', '山西': '山西省', '内蒙古': '内蒙古自治区',
  '辽宁': '辽宁省', '吉林': '吉林省', '黑龙江': '黑龙江省', '上海': '上海市', '江苏': '江苏省',
  '浙江': '浙江省', '安徽': '安徽省', '福建': '福建省', '江西': '江西省', '山东': '山东省',
  '河南': '河南省', '湖北': '湖北省', '湖南': '湖南省', '广东': '广东省', '广西': '广西壮族自治区',
  '海南': '海南省', '重庆': '重庆市', '四川': '四川省', '贵州': '贵州省', '云南': '云南省',
  '西藏': '西藏自治区', '陕西': '陕西省', '甘肃': '甘肃省', '青海': '青海省', '宁夏': '宁夏回族自治区',
  '新疆': '新疆维吾尔自治区', '台湾': '台湾省', '香港': '香港特别行政区', '澳门': '澳门特别行政区',
};

const cityToGeoProvince: Record<string, string> = {
  '大连市': '辽宁省', '大连': '辽宁省', '青岛市': '山东省', '青岛': '山东省',
  '深圳市': '广东省', '深圳': '广东省', '厦门市': '福建省', '厦门': '福建省',
  '宁波市': '浙江省', '宁波': '浙江省'
};

interface ChinaMapProps {
  data: MapItem[];
}

export interface ChinaMapHandle {
  getChartInstance: () => echarts.ECharts | null;
}

const ChinaMap = forwardRef<ChinaMapHandle, ChinaMapProps>(({ data }, ref) => {
  const chartRef = useRef<HTMLDivElement>(null);
  const chartInstance = useRef<echarts.ECharts | null>(null);

  useEffect(() => {
    if (!chartRef.current) return;

    if (!echarts.getMap('china')) {
      // @ts-expect-error - geoJSON type
      echarts.registerMap('china', chinaGeoJSON);
    }

    // Process input data to match GeoJSON region names
    const dataMap: Record<string, number> = {};
    data.forEach(item => {
      let geoName = '';
      const rawName = item.name;
      if (cityToGeoProvince[rawName]) {
        geoName = cityToGeoProvince[rawName];
      } else {
        const shortName = rawName.replace(/(省|市|自治区|维吾尔|壮族|回族|特别行政区)/g, '');
        geoName = geoNameMap[shortName] || geoNameMap[rawName] || rawName;
      }
      
      dataMap[geoName] = (dataMap[geoName] || 0) + item.value;
    });

    const uniqueProvinces = Array.from(new Set(Object.values(geoNameMap)));
    const chartData: any[] = uniqueProvinces.map(name => {
      return { name, value: dataMap[name] || 0 };
    });

    const maxVal = Math.max(...chartData.map(i => i.value), 1);

    // Ensure 南海诸岛 is visible with a subtle style
    if (!chartData.find(d => d.name === '南海诸岛')) {
      chartData.push({
        name: '南海诸岛',
        value: 0,
        itemStyle: {
          areaColor: '#F1F5F9',
          borderWidth: 0
        },
        label: { show: false },
        emphasis: {
          itemStyle: {
            areaColor: '#CBD5E1',
            borderWidth: 0
          }
        }
      });
    }

    const option: echarts.EChartsOption = {
      backgroundColor: 'transparent',
      silent: true,
      animation: false,
      visualMap: {
        show: false,
        min: 0,
        max: maxVal,
        inRange: {
          color: ['#F0F7FF', '#BAE0FF', '#69B1FF', '#1677FF', '#003A8C']
        },
      },
      series: [
        {
          name: '采集数量',
          type: 'map',
          map: 'china',
          roam: false,
          zoom: 1.3
          ,
          layoutCenter: ['50%', '65%'], 
          layoutSize: '100%', 
          label: {
            show: true,
            fontSize: 12,
            color: '#1e293b',
            fontWeight: 'bold',
            textBorderColor: '#fff',
            textBorderWidth: 2,
            formatter: (params: any) => {
              if (['香港特别行政区', '澳门特别行政区', '台湾省'].includes(params.name)) return '';
              const shortName = (params.name as string).replace(/(省|市|自治区|特别行政区|壮族|回族|维吾尔)/g, '');
              const val = params.value as number;
              return val > 0 ? `${shortName}\n{val|${val}}` : shortName;
            },
            rich: {
              val: {
                fontSize: 10,
                fontWeight: 'normal',
                color: '#475569',
                textBorderColor: '#fff',
                textBorderWidth: 2,
                padding: [2, 0, 0, 0]
              }
            }
          },
          itemStyle: {
            borderColor: '#fff',
            borderWidth: 1,
            areaColor: '#f8fafc'
          },
          data: chartData
        }
      ]
    };

    if (!chartInstance.current) {
        chartInstance.current = echarts.init(chartRef.current);
    }
    chartInstance.current.setOption(option);

    return () => {
      // Don't dispose immediately to allow capture, but it's fine in React
    };
  }, [data]);

  // 暴露图表实例给父组件
  useImperativeHandle(ref, () => ({
    getChartInstance: () => chartInstance.current
  }));

  // 将图表实例保存到 DOM 元素上，方便外部访问
  useEffect(() => {
    if (chartInstance.current && chartRef.current) {
      // 将实例保存到 DOM 元素上
      (chartRef.current as any)._echarts_instance = chartInstance.current;
    }
  }, [chartInstance.current]);

  return (
    <div className="echarts-canvas-container relative w-full h-full">
      <div ref={chartRef} className="echarts-inner w-full h-full" data-echarts-instance="true" />
      <img className="echarts-export-image absolute inset-0 w-full h-full object-contain hidden" alt="图表导出图片" />
    </div>
  );
});

export { ChinaMap };
