import React from 'react';
import { 
  Table, Card, Typography
} from 'antd';
import { 
  useQuery,
} from '@tanstack/react-query';
import {  Pie } from "@ant-design/plots";
import 'dayjs/locale/zh-cn';
import type { 
  StateChartDataWithPercent, 
} from '../share/monitorTypes.ts';

import { MonitorChartsAPI } from './api/index.ts';

interface ChartTooltipInfo {
  items: Array<Record<string, any>>;
  title: string;
}

// 资产流转状态图表页面
export const AssetTransferChartPage = () => {
    const { data: stateData, isLoading } = useQuery({
      queryKey: ['adminZichanState'],
      queryFn: MonitorChartsAPI.fetchStateData
    });
  
    const { Title } = Typography;
  
    return (
      <div>
        <Title level={2}>资产流转状态分布</Title>
        <Card loading={isLoading}>
          <div style={{ height: '500px' }}>
            {stateData && (
              <Pie
                data={stateData}
                angleField="设备数"
                colorField="资产流转"
                radius={0.9}
                innerRadius={0.8}
                label={{
                  position: 'outside',
                  text: ({ 资产流转, 设备数, 百分比, percent }: StateChartDataWithPercent & { percent: number }) => {
                    // 只有占比超过5%的项才显示标签
                    if (percent < 0.05) return null;
                    return `${资产流转}\n(${设备数})`;
                  },
                  style: {
                    fill: '#000',
                    fontSize: 12,
                    fontWeight: 500,
                  },
                  transform: [{ type: 'overlapDodgeY' }],
                }}
                theme={{
                  colors10: ['#36cfc9', '#ff4d4f', '#ffa940', '#73d13d', '#4096ff'],
                }}
                interactions={[
                  { type: 'element-active' },
                  { type: 'element-selected' }
                ]}
                interaction={{
                  tooltip: {
                    render: (_: unknown, { items, title }: ChartTooltipInfo) => {
                      if (!items || items.length === 0) return '';
                      
                      // 获取当前选中项的数据
                      const item = items[0];
                      
                      // 根据value找到对应的完整数据项
                      const fullData = stateData?.find(d => d['设备数'] === item.value);
                      if (!fullData) return '';
                      
                      return `<div class="bg-white p-2 rounded">
                        <div class="flex items-center">
                          <div class="w-3 h-3 rounded-full mr-2" style="background:${item.color}"></div>
                          <span class="font-semibold text-gray-900">${fullData['资产流转']}</span>
                        </div>
                        <p class="text-sm text-gray-800">数量: ${item.value}</p>
                        <p class="text-sm text-gray-800">占比: ${fullData['百分比']}%</p>
                      </div>`;
                    }
                  }
                }}
              />
            )}
          </div>
        </Card>
        <Card style={{ marginTop: '16px' }}>
          <Title level={4}>数据明细</Title>
          <Table 
            dataSource={stateData} 
            rowKey={(record) => record['资产流转']}
            columns={[
              {
                title: '资产流转状态',
                dataIndex: '资产流转',
                key: '资产流转',
              },
              {
                title: '设备数量',
                dataIndex: '设备数',
                key: '设备数',
                sorter: (a, b) => a['设备数'] - b['设备数'],
              },
              {
                title: '占比',
                dataIndex: '百分比',
                key: '百分比',
                render: (text) => `${text}%`,
                sorter: (a, b) => parseFloat(a['百分比']) - parseFloat(b['百分比']),
              }
            ]}
            pagination={false}
          />
        </Card>
      </div>
    );
  };