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

const { Option } = Select;

interface KeywordData {
  keyWord: string;
  searchCount: number;
  rank?: number;
}

export default function KeywordChart() {
  const [data, setData] = useState<KeywordData[]>([]);
  const [loading, setLoading] = useState(false);
  const [timeType, setTimeType] = useState<'1' | '2' | '3'>('3');
  const [displayMode, setDisplayMode] = useState<'column' | 'wordcloud'>('column');
  const [totalSearches, setTotalSearches] = useState(0);

  const fetchData = useCallback(async (searchType: '1' | '2' | '3' = '3') => {
    setLoading(true);
    try {
      const resData = await getKeyWordSearchRank({
        searchDate: '2025-11-03',
        searchType: searchType,
      });
      if (resData.code === 200) {
        const formattedData = resData.rows
          .sort((a, b) => b.searchCount - a.searchCount)
          .slice(0, 15)
          .map((item, index) => ({
            ...item,
            searchCount: Number(item.searchCount) || 0,
            rank: index + 1,
          }));
        
        setData(formattedData);
        
        // 计算总搜索次数
        const total = formattedData.reduce((sum, item) => sum + item.searchCount, 0);
        setTotalSearches(total);
      }
    } catch (error) {
      console.error('获取关键词数据失败:', error);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchData(timeType);
  }, [timeType]);

  // 
  const columnConfig = {
    data: data,
    stack:true,
    xField: 'keyWord',
    yField: 'searchCount',
    height: 280,
    autoFit: true,
    style:{
      columnWidthRatio:0.3, 
    },
    // labels: [
    //   {
    //     text: 'searchCount',
    //     style: {
    //       fill: '#666',
    //       fontSize: 12,
    //       fontWeight: 600,
    //       textBaseline: 'bottom',
    //       dy: -6, // 向上偏移，避免与柱状图顶部重叠
    //     },
    //     position: 'top',
    //   }
    // ],
    xAxis: {
      label: {
        autoHide: true,
        autoRotate: false,
        style: {
          fontSize: 12,
          fill: '#666',
        },
        formatter: (text: string) => {
          return text.length > 6 ? `${text.substring(0, 6)}...` : text;
        },
      },
      title: {
        text: '关键词',
        style: {
          fontSize: 14,
          fill: '#333',
          fontWeight: 'bold',
        },
      },
      grid: {
        line: {
          style: {
            stroke: '#e8e8e8',
            lineWidth: 1,
            lineDash: [3, 3],
          },
        },
        alignTick: true, 
      },
    },
    yAxis: {
      title: {
        text: '搜索次数',
        style: {
          fontSize: 14,
          fill: '#333',
          fontWeight: 'bold',
        },
      },
      label: {
        style: {
          fontSize: 12,
          fill: '#666',
        },
      },
      grid: {
        line: {
          style: {
            stroke: '#e8e8e8',
            lineWidth: 1,
            lineDash: [3, 3],
          },
        },
        alignTick: true, 
      },
    },
    tooltip: {
      title: '关键词搜索统计',
      items: [
        { field: 'keyWord', name: '关键词' },
        { field: 'rank', name: '排名' },
        { field: 'searchCount', name: '搜索次数', valueFormatter: (v) => `${v} 次` },
      ],
    },
    interactions: [{ type: 'element-active' }],
    animation: {
      appear: {
        animation: 'scale-in-y',
        duration: 1000,
      },
    },
  };



  const getTimeText = () => {
    switch(timeType) {
      case '1': return '今日';
      case '2': return '本周';
      case '3': return '本月';
      default: return '';
    }
  };

  return (
    <Card
      title={
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span>🔍 查询关键词搜索排行</span>
          <Tag color="purple">搜索分析</Tag>
        </div>
      }
      style={{ 
        borderRadius: 12,
        boxShadow: '0 4px 12px rgba(0,0,0,0.1)'
      }}
      bodyStyle={{ 
        padding: '16px',
        borderRadius: 8
      }}
      extra={
        <Row gutter={[8, 8]} align="middle">
          <Col>
            <Select
              value={timeType}
              onChange={setTimeType}
              style={{ width: 100 }}
            >
              <Option value="1">今日</Option>
              <Option value="2">本周</Option>
              <Option value="3">本月</Option>
            </Select>
          </Col>
        </Row>
      }
    >
      <Spin spinning={loading} tip="数据加载中...">
        {/* 统计信息 */}
        <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
          <Col xs={8}>
            <Card size="small" style={{ background: 'rgba(24, 144, 255, 0.1)', textAlign: 'center' }}>
              <Statistic 
                title="总搜索次数" 
                value={totalSearches}
                suffix="次"
              />
            </Card>
          </Col>
          <Col xs={8}>
            <Card size="small" style={{ background: 'rgba(250, 173, 20, 0.1)', textAlign: 'center' }}>
              <Statistic 
                title="关键词数量" 
                value={data.length}
                suffix="个"
              />
            </Card>
          </Col>
          <Col xs={8}>
            <Card size="small" style={{ background: 'rgba(114, 46, 209, 0.1)', textAlign: 'center' }}>
              <Statistic 
                title="统计时段" 
                value={getTimeText()}
              />
            </Card>
          </Col>
        </Row>

        {/* 图表显示区域 */}
        {data.length > 0 ? (
            <Column {...columnConfig} />
        ) : (
          <Empty
            description="暂无搜索关键词数据"
            style={{ margin: '80px 0' }}
          />
        )}
      </Spin>
    </Card>
  );
}