import { useState, useMemo } from 'react';
import {
  Card,
  Row,
  Col,
  Statistic,
  DatePicker,
  Select,
  Table,
  Tabs,
  Button,
  Space,
  Typography,
  Spin,
  Modal,
  Form,
} from 'antd';
import {
  UserOutlined,
  MessageOutlined,
  DollarOutlined,
  SyncOutlined,
  HistoryOutlined,
} from '@ant-design/icons';
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  Legend,
} from 'recharts';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';
import type { ColumnsType } from 'antd/es/table';
import {
  useDailyStatistics,
  useTrendData,
  useStatisticsByChannel,
  useStatisticsByCategory,
  useRefreshStatistics,
  useBackfillStatistics,
  type DailyStatisticsDto,
} from '../../application';
import { AgentAnalyticsTab } from '../components/AgentAnalyticsTab';

const { Title } = Typography;
const { RangePicker } = DatePicker;

const METRIC_OPTIONS = [
  { value: 'newUsers', label: '新增用户' },
  { value: 'activeUsers', label: '活跃用户' },
  { value: 'newConversations', label: '新增对话' },
  { value: 'totalMessages', label: '消息总数' },
  { value: 'paidOrders', label: '支付订单' },
  { value: 'totalPaidAmount', label: '收入金额' },
  { value: 'conversionRate', label: '转化率' },
  { value: 'estimatedApiCost', label: 'API成本' },
];

const METRIC_COLORS: Record<string, string> = {
  newUsers: '#1890ff',
  activeUsers: '#13c2c2',
  newConversations: '#52c41a',
  totalMessages: '#faad14',
  paidOrders: '#722ed1',
  totalPaidAmount: '#eb2f96',
  conversionRate: '#f5222d',
  estimatedApiCost: '#8c8c8c',
};

export function AnalyticsPage() {
  // Date range state
  const [dateRange, setDateRange] = useState<[Dayjs, Dayjs]>([
    dayjs().subtract(7, 'day'),
    dayjs(),
  ]);

  // Selected metrics for trend chart
  const [selectedMetrics, setSelectedMetrics] = useState<string[]>([
    'newConversations',
    'newUsers',
  ]);

  // Trend days
  const [trendDays, setTrendDays] = useState(7);

  // Backfill modal
  const [backfillModalOpen, setBackfillModalOpen] = useState(false);
  const [backfillForm] = Form.useForm();

  const startDate = dateRange[0].format('YYYY-MM-DD');
  const endDate = dateRange[1].format('YYYY-MM-DD');

  // Queries
  const { data: dailyStats, isLoading: loadingDaily } = useDailyStatistics(
    startDate,
    endDate,
    'OVERALL'
  );
  const { data: trendData, isLoading: loadingTrend } = useTrendData(trendDays, selectedMetrics);
  const { data: channelStats, isLoading: loadingChannel } = useStatisticsByChannel(startDate, endDate);
  const { data: categoryStats, isLoading: loadingCategory } = useStatisticsByCategory(startDate, endDate);

  // Mutations
  const refreshMutation = useRefreshStatistics();
  const backfillMutation = useBackfillStatistics();

  // Calculate summary from daily stats
  const summary = useMemo(() => {
    if (!dailyStats || dailyStats.length === 0) {
      return {
        newUsers: 0,
        newConversations: 0,
        paidOrders: 0,
        totalPaidAmount: 0,
        estimatedApiCost: 0,
      };
    }
    return dailyStats.reduce(
      (acc, stat) => ({
        newUsers: acc.newUsers + stat.newUsers,
        newConversations: acc.newConversations + stat.newConversations,
        paidOrders: acc.paidOrders + stat.paidOrders,
        totalPaidAmount: acc.totalPaidAmount + stat.totalPaidAmount,
        estimatedApiCost: acc.estimatedApiCost + stat.estimatedApiCost,
      }),
      { newUsers: 0, newConversations: 0, paidOrders: 0, totalPaidAmount: 0, estimatedApiCost: 0 }
    );
  }, [dailyStats]);

  // Transform trend data for chart
  const chartData = useMemo(() => {
    if (!trendData || selectedMetrics.length === 0) return [];
    const firstMetric = selectedMetrics[0];
    if (!trendData[firstMetric]) return [];

    return trendData[firstMetric].map((d, i) => {
      const point: Record<string, string | number> = { date: d.date.slice(5) };
      selectedMetrics.forEach((metric) => {
        point[metric] = trendData[metric]?.[i]?.value || 0;
      });
      return point;
    });
  }, [trendData, selectedMetrics]);

  // Table columns for dimension breakdown
  const dimensionColumns: ColumnsType<DailyStatisticsDto> = [
    {
      title: '维度值',
      dataIndex: 'dimensionValue',
      key: 'dimensionValue',
      render: (v) => v || '-',
    },
    { title: '新增用户', dataIndex: 'newUsers', key: 'newUsers' },
    { title: '新增对话', dataIndex: 'newConversations', key: 'newConversations' },
    { title: '支付订单', dataIndex: 'paidOrders', key: 'paidOrders' },
    {
      title: '收入金额',
      dataIndex: 'totalPaidAmount',
      key: 'totalPaidAmount',
      render: (v) => `¥${Number(v).toFixed(2)}`,
    },
    {
      title: '转化率',
      dataIndex: 'conversionRate',
      key: 'conversionRate',
      render: (v) => `${(Number(v) * 100).toFixed(1)}%`,
    },
    {
      title: 'API成本',
      dataIndex: 'estimatedApiCost',
      key: 'estimatedApiCost',
      render: (v) => `$${Number(v).toFixed(2)}`,
    },
  ];

  const handleRefresh = () => {
    refreshMutation.mutate(undefined);
  };

  const handleBackfill = async () => {
    try {
      const values = await backfillForm.validateFields();
      const [start, end] = values.dateRange;
      backfillMutation.mutate({
        startDate: start.format('YYYY-MM-DD'),
        endDate: end.format('YYYY-MM-DD'),
      });
      setBackfillModalOpen(false);
      backfillForm.resetFields();
    } catch {
      // Form validation failed
    }
  };

  return (
    <div className="p-6">
      <div className="flex items-center justify-between mb-6">
        <Title level={4} className="mb-0">统计分析</Title>
        <Space>
          <Button
            icon={<SyncOutlined />}
            onClick={handleRefresh}
            loading={refreshMutation.isPending}
          >
            刷新今日
          </Button>
          <Button
            icon={<HistoryOutlined />}
            onClick={() => setBackfillModalOpen(true)}
          >
            历史回填
          </Button>
        </Space>
      </div>

      {/* Date Range Filter */}
      <Card className="mb-4">
        <Space>
          <span>日期范围：</span>
          <RangePicker
            value={dateRange}
            onChange={(dates) => {
              if (dates && dates[0] && dates[1]) {
                setDateRange([dates[0], dates[1]]);
              }
            }}
          />
        </Space>
      </Card>

      {/* Summary Statistics */}
      <Card title="统计概览" className="mb-4">
        <Spin spinning={loadingDaily}>
          <Row gutter={[16, 16]}>
            <Col xs={24} sm={12} lg={6}>
              <Statistic
                title="新增用户"
                value={summary.newUsers}
                prefix={<UserOutlined />}
                valueStyle={{ color: '#1890ff' }}
              />
            </Col>
            <Col xs={24} sm={12} lg={6}>
              <Statistic
                title="新增对话"
                value={summary.newConversations}
                prefix={<MessageOutlined />}
                valueStyle={{ color: '#52c41a' }}
              />
            </Col>
            <Col xs={24} sm={12} lg={6}>
              <Statistic
                title="支付订单"
                value={summary.paidOrders}
                valueStyle={{ color: '#722ed1' }}
              />
            </Col>
            <Col xs={24} sm={12} lg={6}>
              <Statistic
                title="总收入"
                value={summary.totalPaidAmount}
                prefix={<DollarOutlined />}
                suffix="元"
                precision={2}
                valueStyle={{ color: '#faad14' }}
              />
            </Col>
          </Row>
        </Spin>
      </Card>

      {/* Trend Analysis */}
      <Card title="趋势分析" className="mb-4">
        <div className="mb-4">
          <Space>
            <span>时间跨度：</span>
            <Select
              value={trendDays}
              onChange={setTrendDays}
              options={[
                { value: 7, label: '7天' },
                { value: 14, label: '14天' },
                { value: 30, label: '30天' },
              ]}
              style={{ width: 100 }}
            />
            <span className="ml-4">指标：</span>
            <Select
              mode="multiple"
              value={selectedMetrics}
              onChange={setSelectedMetrics}
              options={METRIC_OPTIONS}
              style={{ minWidth: 300 }}
              maxTagCount={3}
            />
          </Space>
        </div>
        <Spin spinning={loadingTrend}>
          <ResponsiveContainer width="100%" height={400}>
            <LineChart data={chartData}>
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis dataKey="date" />
              <YAxis />
              <Tooltip />
              <Legend />
              {selectedMetrics.map((metric) => (
                <Line
                  key={metric}
                  type="monotone"
                  dataKey={metric}
                  stroke={METRIC_COLORS[metric] || '#1890ff'}
                  name={METRIC_OPTIONS.find((o) => o.value === metric)?.label || metric}
                />
              ))}
            </LineChart>
          </ResponsiveContainer>
        </Spin>
      </Card>

      {/* Dimension Breakdown */}
      <Card title="维度对比">
        <Tabs
          items={[
            {
              key: 'channel',
              label: '按渠道',
              children: (
                <Spin spinning={loadingChannel}>
                  <Table
                    columns={dimensionColumns}
                    dataSource={channelStats || []}
                    rowKey={(r) => r.dimensionValue || 'unknown'}
                    pagination={false}
                  />
                </Spin>
              ),
            },
            {
              key: 'category',
              label: '按类别',
              children: (
                <Spin spinning={loadingCategory}>
                  <Table
                    columns={dimensionColumns}
                    dataSource={categoryStats || []}
                    rowKey={(r) => r.dimensionValue || 'unknown'}
                    pagination={false}
                  />
                </Spin>
              ),
            },
            {
              key: 'agents',
              label: 'Agent 使用分析',
              children: <AgentAnalyticsTab />,
            },
          ]}
        />
      </Card>

      {/* Backfill Modal */}
      <Modal
        title="历史数据回填"
        open={backfillModalOpen}
        onOk={handleBackfill}
        onCancel={() => setBackfillModalOpen(false)}
        confirmLoading={backfillMutation.isPending}
      >
        <Form form={backfillForm} layout="vertical">
          <Form.Item
            name="dateRange"
            label="回填日期范围"
            rules={[{ required: true, message: '请选择日期范围' }]}
          >
            <RangePicker style={{ width: '100%' }} />
          </Form.Item>
          <p className="text-gray-500 text-sm">
            回填操作会重新计算指定日期范围内的统计数据，可能需要较长时间。
          </p>
        </Form>
      </Modal>
    </div>
  );
}
