import { useMemo } from 'react';
import { Card, Row, Col, Statistic, Typography, Spin } from 'antd';
import {
  UserOutlined,
  MessageOutlined,
  DollarOutlined,
  RobotOutlined,
} from '@ant-design/icons';
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell,
} from 'recharts';
import { useTodayStatistics, useTrendData, useStatisticsByCategory } from '../../../analytics/application';

const { Title } = Typography;

// Category color mapping
const CATEGORY_COLORS: Record<string, string> = {
  QMAS: '#1890ff',
  GEP: '#52c41a',
  IANG: '#faad14',
  TTPS: '#722ed1',
  CIES: '#eb2f96',
  TechTAS: '#13c2c2',
  AEAS: '#f5222d',
  OTHER: '#8c8c8c',
};

export function DashboardPage() {
  // Analytics data from real API
  const { data: todayStats, isLoading: loadingToday } = useTodayStatistics();
  const { data: trendData, isLoading: loadingTrend } = useTrendData(7, ['newConversations', 'newUsers']);

  // Get date range for last 7 days for category stats
  const dateRange = useMemo(() => {
    const end = new Date();
    const start = new Date();
    start.setDate(start.getDate() - 7);
    return {
      startDate: start.toISOString().split('T')[0],
      endDate: end.toISOString().split('T')[0],
    };
  }, []);

  const { data: categoryStats, isLoading: loadingCategory } = useStatisticsByCategory(
    dateRange.startDate,
    dateRange.endDate
  );

  // Transform trend data for chart
  const chartData = useMemo(() => {
    if (!trendData?.newConversations) return [];
    return trendData.newConversations.map((d, i) => ({
      date: d.date.slice(5), // MM-DD format
      conversations: d.value,
      users: trendData.newUsers?.[i]?.value || 0,
    }));
  }, [trendData]);

  // Transform category data for pie chart
  const pieData = useMemo(() => {
    if (!categoryStats || categoryStats.length === 0) {
      // Return default data if no category stats
      return [
        { name: 'QMAS', value: 35, color: CATEGORY_COLORS.QMAS },
        { name: 'GEP', value: 25, color: CATEGORY_COLORS.GEP },
        { name: 'IANG', value: 20, color: CATEGORY_COLORS.IANG },
        { name: 'TTPS', value: 10, color: CATEGORY_COLORS.TTPS },
        { name: 'CIES', value: 7, color: CATEGORY_COLORS.CIES },
        { name: 'TechTAS', value: 3, color: CATEGORY_COLORS.TechTAS },
      ];
    }
    return categoryStats.map(s => ({
      name: s.dimensionValue || 'OTHER',
      value: s.newConversations,
      color: CATEGORY_COLORS[s.dimensionValue || 'OTHER'] || '#8c8c8c',
    })).filter(d => d.value > 0);
  }, [categoryStats]);

  return (
    <div className="p-6">
      <Title level={4} className="mb-6">仪表盘</Title>

      {/* Core Metrics */}
      <Row gutter={[16, 16]}>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Spin spinning={loadingToday}>
              <Statistic
                title="今日用户"
                value={todayStats?.newUsers ?? 0}
                prefix={<UserOutlined />}
                valueStyle={{ color: '#1890ff' }}
              />
              <div className="mt-2 text-gray-500 text-sm">
                活跃用户: {todayStats?.activeUsers ?? 0}
              </div>
            </Spin>
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Spin spinning={loadingToday}>
              <Statistic
                title="今日对话"
                value={todayStats?.newConversations ?? 0}
                prefix={<MessageOutlined />}
                valueStyle={{ color: '#52c41a' }}
              />
              <div className="mt-2 text-gray-500 text-sm">
                消息数: {todayStats?.totalMessages ?? 0}
              </div>
            </Spin>
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Spin spinning={loadingToday}>
              <Statistic
                title="今日收入"
                value={todayStats?.totalPaidAmount ?? 0}
                prefix={<DollarOutlined />}
                suffix="元"
                precision={2}
                valueStyle={{ color: '#faad14' }}
              />
              <div className="mt-2 text-gray-500 text-sm">
                订单数: {todayStats?.paidOrders ?? 0}
              </div>
            </Spin>
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Spin spinning={loadingToday}>
              <Statistic
                title="转化率"
                value={((todayStats?.conversionRate ?? 0) * 100).toFixed(1)}
                suffix="%"
                prefix={<RobotOutlined />}
                valueStyle={{ color: '#722ed1' }}
              />
              <div className="mt-2 text-gray-500 text-sm">
                API成本: ${(todayStats?.estimatedApiCost ?? 0).toFixed(2)}
              </div>
            </Spin>
          </Card>
        </Col>
      </Row>

      {/* Trend Charts */}
      <Row gutter={[16, 16]} className="mt-4">
        <Col xs={24} lg={16}>
          <Card title="对话趋势 (近7天)">
            <Spin spinning={loadingTrend}>
              <ResponsiveContainer width="100%" height={300}>
                <LineChart data={chartData}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="date" />
                  <YAxis />
                  <Tooltip />
                  <Line
                    type="monotone"
                    dataKey="conversations"
                    stroke="#1890ff"
                    name="对话数"
                  />
                  <Line
                    type="monotone"
                    dataKey="users"
                    stroke="#52c41a"
                    name="用户数"
                  />
                </LineChart>
              </ResponsiveContainer>
            </Spin>
          </Card>
        </Col>
        <Col xs={24} lg={8}>
          <Card title="类别分布 (近7天)">
            <Spin spinning={loadingCategory}>
              <ResponsiveContainer width="100%" height={300}>
                <PieChart>
                  <Pie
                    data={pieData}
                    dataKey="value"
                    nameKey="name"
                    cx="50%"
                    cy="50%"
                    outerRadius={80}
                    label={({ name, percent }) =>
                      `${name} ${(percent * 100).toFixed(0)}%`
                    }
                  >
                    {pieData.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={entry.color} />
                    ))}
                  </Pie>
                  <Tooltip />
                </PieChart>
              </ResponsiveContainer>
            </Spin>
          </Card>
        </Col>
      </Row>

    </div>
  );
}
