import { Spin, message } from 'antd';
import ReactECharts from 'echarts-for-react';
import { MapChart } from 'echarts/charts';
import { TooltipComponent, VisualMapComponent } from 'echarts/components';
import * as echarts from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import React, { useEffect, useState } from 'react';

// 注册 ECharts 组件
echarts.use([TooltipComponent, VisualMapComponent, MapChart, CanvasRenderer]);

interface ProvinceData {
  name: string; // 英文名称（用于匹配地图）
  chineseName: string; // 中文名称
  shortName: string; // 简称
  population: number; // 人口数据
}

const AustraliaMap: React.FC = () => {
  const [option, setOption] = useState({});
  const [loading, setLoading] = useState(true);

  // 澳大利亚省级数据
  const provinceData: ProvinceData[] = [
    { name: 'New South Wales', chineseName: '新南威尔士州', shortName: 'NSW', population: 8166369 },
    { name: 'Victoria', chineseName: '维多利亚州', shortName: 'VIC', population: 6704352 },
    { name: 'Queensland', chineseName: '昆士兰州', shortName: 'QLD', population: 5265049 },
    { name: 'Western Australia', chineseName: '西澳大利亚州', shortName: 'WA', population: 2885548 },
    { name: 'South Australia', chineseName: '南澳大利亚州', shortName: 'SA', population: 1806604 },
    { name: 'Tasmania', chineseName: '塔斯马尼亚州', shortName: 'TAS', population: 569825 },
    { name: 'Australian Capital Territory', chineseName: '澳大利亚首都领地', shortName: 'ACT', population: 453349 },
    { name: 'Northern Territory', chineseName: '北领地', shortName: 'NT', population: 249072 },
  ];

  useEffect(() => {
    const fetchAndSetMapData = async () => {
      try {
        // 加载澳大利亚地图数据
        const australiaMapResponse = await fetch('/australia.json');
        const australiaMap = await australiaMapResponse.json();
        echarts.registerMap('australia', australiaMap);

        // 将省级数据转换为 ECharts 需要的格式
        const mapData = provinceData.map((province) => ({
          name: province.name,
          value: province.population,
          chineseName: province.chineseName,
          shortName: province.shortName,
          population: province.population,
        }));

        // 配置 ECharts 地图选项
        const mapOption = {
          tooltip: {
            trigger: 'item',
            formatter: (params: any) => {
              if (params.data) {
                return `
                  <div>
                    <div><strong>${params.data.chineseName}</strong> (${params.data.shortName})</div>
                    <div>人口: ${params.data.population.toLocaleString()}</div>
                  </div>
                `;
              }
              return `${params.name}`;
            },
          },
          visualMap: {
            left: 'left',
            min: Math.min(...provinceData.map(p => p.population)),
            max: Math.max(...provinceData.map(p => p.population)),
            inRange: {
              color: ['#f0f0f0', '#52c41a', '#389e0d'],
            },
            calculable: true,
            orient: 'vertical',
            left: 'right',
            top: 'center',
            text: ['人口多', '人口少'],
          },
          series: [
            {
              name: 'Australia States',
              type: 'map',
              map: 'australia',
              roam: true,
              nameProperty: 'STATE_NAME', // 指定地图数据中用于匹配的字段
              label: {
                show: true,
                formatter: (params: any) => {
                  if (params.data) {
                    return `${params.data.shortName}\n${params.data.chineseName}\n${params.data.population.toLocaleString()}`;
                  }
                  return params.name;
                },
                fontSize: 12,
                color: '#333',
                fontWeight: 'bold',
              },
              emphasis: {
                label: {
                  show: true,
                },
                itemStyle: {
                  areaColor: '#ffc107',
                },
              },
              data: mapData,
            },
          ],
        };

        setOption(mapOption);
      } catch (error: any) {
        message.error(`加载地图数据失败: ${error.message}`);
      } finally {
        setLoading(false);
      }
    };

    fetchAndSetMapData();
  }, []);

  if (loading) {
    return (
      <Spin
        size="large"
        style={{
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          height: '80vh',
        }}
      />
    );
  }

  return (
    <ReactECharts
      echarts={echarts}
      option={option}
      style={{ height: '80vh', width: '100%' }}
      notMerge={true}
      lazyUpdate={true}
    />
  );
};

export default AustraliaMap;