import React, { useState, useEffect, useCallback } from 'react';
import { Card, Select, Row, Col, Statistic, Tag, Empty, Spin } from 'antd';
import { getUserStaticsByArea } from '@/services/analysis/user';
import { Column, Pie } from '@ant-design/charts';

const { Option } = Select;

export default function AreaStatics({ data }) {
  const [selectedArea, setSelectedArea] = useState('');
  const [byArea, setByArea] = useState({});
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (data.length > 0) {
      setSelectedArea(data[0].dictValue);
      fetchAreaStatics(data[0].dictValue);
    }
  }, [data]);

  const fetchAreaStatics = async (areaCode) => {
    setLoading(true);
    try {
      const resData = await getUserStaticsByArea(areaCode);
      if (resData.code === 200) {
        const processedData = {
          gender: transformNum(resData.data.gender),
          education: transformNum(resData.data.education),
          position: transformNum(resData.data.position),
          salary: transformNum(resData.data.salary),
          age: transformNum(resData.data.age),
        };
        setByArea(processedData);
      }
    } catch (error) {
      console.error('获取区域数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const transformNum = useCallback((datas) => {
    return (datas || []).map((item) => ({ ...item, data: parseInt(item.data) || 0 }));
  }, []);

  const handleAreaChange = (value) => {
    setSelectedArea(value);
    fetchAreaStatics(value);
  };

  // 统一的柱状图配置
  const getColumnConfig = (data: any[], color: string, title: string) => ({
    data: data || [],
    xField: 'name',
    yField: 'data',
    height: 220,
    autoFit: true,
    style:{
      columnWidthRatio: 0.4, 
    },
    axis: {
      x: {
        labelFontSize:11,
        labelAutoRotate:true,
        labelFormatter:(str)=>str.replace('（含）','')
      },
    },
    tooltip: {
      title: title,
      items: [
        { field: 'name', name: '分类' },
        { field: 'data', name: '人数', valueFormatter: (v) => `${v} 人` },
      ],
    },
    interactions: [{ type: 'element-active' }],
    animation: {
      appear: {
        animation: 'scale-in-y',
        duration: 1000,
      },
    },
  });

  // 教育程度柱状图配置
  const educationConfig = getColumnConfig(byArea.education, '#36cfc9', '学历分布');

  // 期望薪资柱状图配置
  const salaryConfig = getColumnConfig(byArea.salary, '#faad14', '期望薪资分布');

  // 年龄分布柱状图配置
  const ageConfig = getColumnConfig(byArea.age, '#722ed1', '年龄分布');

  // 性别饼图配置
  const genderConfig = {
    data: byArea.gender || [],
    angleField: 'data',
    colorField: 'name',
    radius: 0.6,
    height: 220,
    label: {
      text: (d) => `${d.name}\n${d.data}人`,
      position: 'spider',
      style: {
        fontSize: 12,
        textAlign: 'center',
      },
      transform: [
        {
          type: 'overlapDodgeY',
        },
      ],
    },
    tooltip: {
      title: '性别分布',
      items: [
        { field: 'name', name: '性别' },
        { field: 'data', name: '人数', valueFormatter: (v) => `${v} 人` },
      ],
    },
    interactions: [{ type: 'element-active' }],
    animation: {
      appear: {
        animation: 'wave-in',
        duration: 1000,
      },
    },
  };

  // 计算用户总数
  const totalUsers = byArea.gender ? byArea.gender.reduce((acc, cur) => acc + cur.data, 0) : 0;

  return (
    <Card
      title={
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span>🌍 区域用户统计</span>
          <Tag color="green">区域分析</Tag>
        </div>
      }
      style={{ 
        borderRadius: 12,
        boxShadow: '0 4px 12px rgba(0,0,0,0.1)'
      }}
      bodyStyle={{ 
        padding: '16px',
        background: 'linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%)',
        borderRadius: 8
      }}
    >
      <Spin spinning={loading} tip="数据加载中...">
        <div style={{ marginBottom: 16 }}>
          <Row gutter={[16, 16]} align="middle">
            <Col xs={24} md={8}>
              <Select
                style={{ width: '100%' }}
                placeholder="选择区域"
                onChange={handleAreaChange}
                value={selectedArea}
                suffixIcon="📍"
              >
                {data.map((item) => (
                  <Option key={item.dictValue} value={item.dictValue}>
                    {item.dictLabel}
                  </Option>
                ))}
              </Select>
            </Col>
            <Col xs={24} md={16}>
              {byArea.gender && byArea.gender.length > 0 ? (
                <Row gutter={[16, 16]}>
                  <Col xs={8}>
                    <Card size="small" style={{ background: 'rgba(24, 144, 255, 0.1)' }}>
                      <Statistic 
                        title="总用户数" 
                        value={totalUsers}
                        suffix="人"
                      />
                    </Card>
                  </Col>
                  <Col xs={8}>
                    <Card size="small" style={{ background: 'rgba(64, 169, 255, 0.1)' }}>
                      <Statistic 
                        title="男性用户" 
                        value={byArea.gender.find(item => item.name === '男')?.data || 0}
                        suffix="人"
                      />
                    </Card>
                  </Col>
                  <Col xs={8}>
                    <Card size="small" style={{ background: 'rgba(235, 47, 150, 0.1)' }}>
                      <Statistic 
                        title="女性用户" 
                        value={byArea.gender.find(item => item.name === '女')?.data || 0}
                        suffix="人"
                      />
                    </Card>
                  </Col>
                </Row>
              ) : (
                <div style={{ textAlign: 'center', padding: 20 }}>
                  暂无用户数据
                </div>
              )}
            </Col>
          </Row>
        </div>

        {byArea.education && byArea.education.length > 0 ? (
          <Row gutter={[16, 16]}>
            {/* 学历分布 */}
            <Col xs={24} md={14}>
              <Card 
                title="🎓 学历分布" 
                size="small"
                style={{ height: '100%' }}
              >
                <Column {...educationConfig} />
              </Card>
            </Col>

            {/* 性别分布 */}
            <Col xs={24} md={5}>
              <Card 
                title="👥 性别分布" 
                size="small"
                style={{ height: '100%' }}
              >
                <Pie {...genderConfig} />
              </Card>
            </Col>

            {/* 年龄分布 */}
            <Col xs={24} md={5}>
              <Card 
                title="📊 年龄分布" 
                size="small"
                style={{ height: '100%' }}
              >
                <Column {...ageConfig} />
              </Card>
            </Col>

            {/* 期望薪资 */}
            <Col xs={24}>
              <Card 
                title="💰 期望薪资分布" 
                size="small"
                style={{ marginTop: 16 }}
              >
                <Column {...salaryConfig} />
              </Card>
            </Col>
          </Row>
        ) : (
          <Empty
            description={selectedArea ? "该区域暂无用户数据" : "请选择区域"}
            style={{ margin: '40px 0' }}
          />
        )}
      </Spin>
    </Card>
  );
}