import { useState, useMemo } from 'react';
import {
  Card,
  Row,
  Col,
  Statistic,
  Table,
  Tag,
  Select,
  Space,
  Spin,
  Progress,
} from 'antd';
import {
  RobotOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  ThunderboltOutlined,
} from '@ant-design/icons';
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  Legend,
} from 'recharts';
import type { ColumnsType } from 'antd/es/table';
import {
  useAgentStatistics,
  useAgentTrend,
  type AgentStatisticsDto,
} from '../../../conversations/application/useConversations';

const AGENT_COLORS: Record<string, string> = {
  policy_expert: '#1890ff',
  assessment_expert: '#52c41a',
  strategist: '#722ed1',
  objection_handler: '#eb2f96',
  case_analyst: '#faad14',
  memory_manager: '#13c2c2',
};

const AGENT_LABELS: Record<string, string> = {
  policy_expert: '政策专家',
  assessment_expert: '评估专家',
  strategist: '策略顾问',
  objection_handler: '异议处理',
  case_analyst: '案例分析',
  memory_manager: '记忆管理',
};

export function AgentAnalyticsTab() {
  const [days, setDays] = useState(30);
  const [trendDays, setTrendDays] = useState(7);

  const { data: agentStats, isLoading: loadingStats } = useAgentStatistics(days);
  const { data: trendData, isLoading: loadingTrend } = useAgentTrend(trendDays);

  // Summary calculations
  const summary = useMemo(() => {
    if (!agentStats || agentStats.length === 0) {
      return { totalCalls: 0, overallSuccessRate: 0, avgDuration: 0, topAgent: '-' };
    }
    const totalCalls = agentStats.reduce((sum, a) => sum + a.totalCalls, 0);
    const totalSuccess = agentStats.reduce((sum, a) => sum + a.successCount, 0);
    const weightedDuration = agentStats.reduce((sum, a) => sum + a.avgDurationMs * a.totalCalls, 0);
    const topAgent = agentStats.reduce((top, a) => (a.totalCalls > top.totalCalls ? a : top), agentStats[0]);

    return {
      totalCalls,
      overallSuccessRate: totalCalls > 0 ? parseFloat(((totalSuccess / totalCalls) * 100).toFixed(1)) : 0,
      avgDuration: totalCalls > 0 ? Math.round(weightedDuration / totalCalls) : 0,
      topAgent: AGENT_LABELS[topAgent.agentType] || topAgent.agentName,
    };
  }, [agentStats]);

  // Transform trend data for chart: pivot by date
  const chartData = useMemo(() => {
    if (!trendData || trendData.length === 0) return [];
    const dateMap = new Map<string, Record<string, number>>();
    for (const item of trendData) {
      const dateStr = typeof item.date === 'string' ? item.date.slice(0, 10) : String(item.date);
      if (!dateMap.has(dateStr)) {
        dateMap.set(dateStr, { date: dateStr as unknown as number });
      }
      const entry = dateMap.get(dateStr)!;
      entry[item.agentType] = item.calls;
    }
    return Array.from(dateMap.values()).map(entry => ({
      ...entry,
      date: String(entry.date).slice(5), // MM-DD format
    }));
  }, [trendData]);

  // Get unique agent types from trend data
  const trendAgentTypes = useMemo(() => {
    if (!trendData) return [];
    return [...new Set(trendData.map(d => d.agentType))];
  }, [trendData]);

  const columns: ColumnsType<AgentStatisticsDto> = [
    {
      title: 'Agent',
      dataIndex: 'agentType',
      key: 'agentType',
      render: (type: string, record) => (
        <Tag color={AGENT_COLORS[type] || 'blue'}>
          {AGENT_LABELS[type] || record.agentName}
        </Tag>
      ),
    },
    {
      title: '调用次数',
      dataIndex: 'totalCalls',
      key: 'totalCalls',
      sorter: (a, b) => a.totalCalls - b.totalCalls,
      defaultSortOrder: 'descend',
    },
    {
      title: '成功率',
      dataIndex: 'successRate',
      key: 'successRate',
      render: (rate: number) => (
        <Progress
          percent={rate}
          size="small"
          status={rate >= 95 ? 'success' : rate >= 80 ? 'normal' : 'exception'}
          format={(p) => `${p}%`}
        />
      ),
      sorter: (a, b) => a.successRate - b.successRate,
    },
    {
      title: '平均耗时',
      dataIndex: 'avgDurationMs',
      key: 'avgDurationMs',
      render: (ms: number) => `${(ms / 1000).toFixed(2)}s`,
      sorter: (a, b) => a.avgDurationMs - b.avgDurationMs,
    },
    {
      title: '最短',
      dataIndex: 'minDurationMs',
      key: 'minDurationMs',
      render: (ms: number) => `${(ms / 1000).toFixed(2)}s`,
    },
    {
      title: '最长',
      dataIndex: 'maxDurationMs',
      key: 'maxDurationMs',
      render: (ms: number) => `${(ms / 1000).toFixed(2)}s`,
    },
    {
      title: '失败',
      dataIndex: 'failureCount',
      key: 'failureCount',
      render: (count: number) =>
        count > 0 ? <Tag color="red">{count}</Tag> : <span className="text-gray-300">0</span>,
    },
  ];

  return (
    <div>
      {/* Summary Cards */}
      <Row gutter={[16, 16]} className="mb-4">
        <Col xs={24} sm={12} lg={6}>
          <Card size="small">
            <Statistic
              title="总调用次数"
              value={summary.totalCalls}
              prefix={<RobotOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card size="small">
            <Statistic
              title="整体成功率"
              value={summary.overallSuccessRate}
              suffix="%"
              prefix={<CheckCircleOutlined />}
              valueStyle={{ color: summary.overallSuccessRate >= 95 ? '#52c41a' : '#faad14' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card size="small">
            <Statistic
              title="平均耗时"
              value={(summary.avgDuration / 1000).toFixed(2)}
              suffix="s"
              prefix={<ClockCircleOutlined />}
              valueStyle={{ color: '#722ed1' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card size="small">
            <Statistic
              title="最常用 Agent"
              value={summary.topAgent}
              prefix={<ThunderboltOutlined />}
              valueStyle={{ color: '#eb2f96', fontSize: 18 }}
            />
          </Card>
        </Col>
      </Row>

      {/* Agent Statistics Table */}
      <Card
        title="Agent 调用统计"
        className="mb-4"
        extra={
          <Space>
            <span>时间范围：</span>
            <Select
              value={days}
              onChange={setDays}
              options={[
                { value: 7, label: '7天' },
                { value: 14, label: '14天' },
                { value: 30, label: '30天' },
                { value: 90, label: '90天' },
              ]}
              style={{ width: 100 }}
            />
          </Space>
        }
      >
        <Spin spinning={loadingStats}>
          <Table
            columns={columns}
            dataSource={agentStats || []}
            rowKey="agentType"
            pagination={false}
            size="middle"
          />
        </Spin>
      </Card>

      {/* Trend Chart */}
      <Card
        title="Agent 调用趋势"
        extra={
          <Space>
            <span>时间跨度：</span>
            <Select
              value={trendDays}
              onChange={setTrendDays}
              options={[
                { value: 7, label: '7天' },
                { value: 14, label: '14天' },
                { value: 30, label: '30天' },
              ]}
              style={{ width: 100 }}
            />
          </Space>
        }
      >
        <Spin spinning={loadingTrend}>
          <ResponsiveContainer width="100%" height={350}>
            <BarChart data={chartData}>
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis dataKey="date" />
              <YAxis />
              <Tooltip />
              <Legend />
              {trendAgentTypes.map((agentType) => (
                <Bar
                  key={agentType}
                  dataKey={agentType}
                  name={AGENT_LABELS[agentType] || agentType}
                  fill={AGENT_COLORS[agentType] || '#8884d8'}
                  stackId="agents"
                />
              ))}
            </BarChart>
          </ResponsiveContainer>
        </Spin>
      </Card>
    </div>
  );
}
