import { useState } from 'react';
import {
  Card,
  Table,
  Tag,
  Space,
  Select,
  DatePicker,
  Row,
  Col,
  Statistic,
  Typography,
  Drawer,
  Descriptions,
  Spin,
  List,
  Tooltip,
} from 'antd';
import {
  MessageOutlined,
  CheckCircleOutlined,
  GlobalOutlined,
  LaptopOutlined,
  BarChartOutlined,
  DollarOutlined,
  ApiOutlined,
  ThunderboltOutlined,
  RobotOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import {
  useConversations,
  useConversationStatistics,
  useConversationDetail,
  useConversationMessages,
  useConversationAgentExecutions,
  type ConversationDto,
  type ConversationStatus,
  type ConversationQueryParams,
  type MessageDto,
  type AgentExecutionDto,
} from '../../application';

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

const STATUS_COLORS: Record<ConversationStatus, string> = {
  ACTIVE: 'green',
  ENDED: 'default',
  ARCHIVED: 'gray',
};

const STATUS_LABELS: Record<ConversationStatus, string> = {
  ACTIVE: '进行中',
  ENDED: '已结束',
  ARCHIVED: '已归档',
};

export function ConversationsPage() {
  const [filters, setFilters] = useState<ConversationQueryParams>({
    page: 1,
    pageSize: 20,
    sortBy: 'createdAt',
    sortOrder: 'DESC',
  });

  const [dateRange, setDateRange] = useState<[dayjs.Dayjs | null, dayjs.Dayjs | null] | null>(null);
  const [detailDrawerOpen, setDetailDrawerOpen] = useState(false);
  const [selectedConversationId, setSelectedConversationId] = useState<string | null>(null);

  // Queries
  const { data: conversationsData, isLoading: loadingConversations } = useConversations(filters);
  const { data: stats, isLoading: loadingStats } = useConversationStatistics();
  const { data: conversationDetail, isLoading: loadingDetail } = useConversationDetail(
    selectedConversationId || '',
    !!selectedConversationId && detailDrawerOpen
  );
  const { data: messages, isLoading: loadingMessages } = useConversationMessages(
    selectedConversationId || '',
    !!selectedConversationId && detailDrawerOpen
  );
  const { data: agentExecutions, isLoading: loadingAgentExecs } = useConversationAgentExecutions(
    selectedConversationId || '',
    !!selectedConversationId && detailDrawerOpen
  );

  const showConversationDetail = (conv: ConversationDto) => {
    setSelectedConversationId(conv.id);
    setDetailDrawerOpen(true);
  };

  const handleDateRangeChange = (dates: [dayjs.Dayjs | null, dayjs.Dayjs | null] | null) => {
    setDateRange(dates);
    if (dates && dates[0] && dates[1]) {
      setFilters((prev) => ({
        ...prev,
        startDate: dates[0]!.format('YYYY-MM-DD'),
        endDate: dates[1]!.format('YYYY-MM-DD'),
        page: 1,
      }));
    } else {
      setFilters((prev) => ({
        ...prev,
        startDate: undefined,
        endDate: undefined,
        page: 1,
      }));
    }
  };

  const handleTableChange = (pagination: { current?: number; pageSize?: number }) => {
    setFilters((prev) => ({
      ...prev,
      page: pagination.current || 1,
      pageSize: pagination.pageSize || 20,
    }));
  };

  const columns: ColumnsType<ConversationDto> = [
    {
      title: '对话',
      key: 'conversation',
      render: (_, record) => (
        <div>
          <div className="font-medium">{record.title || '未命名对话'}</div>
          <div className="text-xs text-gray-500">ID: {record.id.slice(0, 8)}...</div>
        </div>
      ),
    },
    {
      title: '用户',
      dataIndex: 'userId',
      key: 'userId',
      width: 120,
      render: (userId) => (
        <Tooltip title={userId}>
          <code className="text-xs">{userId.slice(0, 8)}...</code>
        </Tooltip>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: ConversationStatus) => (
        <Tag color={STATUS_COLORS[status]}>{STATUS_LABELS[status]}</Tag>
      ),
    },
    {
      title: '消息数',
      dataIndex: 'messageCount',
      key: 'messageCount',
      width: 80,
      align: 'center',
    },
    {
      title: '转化',
      dataIndex: 'hasConverted',
      key: 'hasConverted',
      width: 80,
      align: 'center',
      render: (converted) =>
        converted ? (
          <CheckCircleOutlined style={{ color: '#52c41a' }} />
        ) : (
          <span className="text-gray-300">-</span>
        ),
    },
    {
      title: '访问IP',
      key: 'ip',
      width: 140,
      render: (_, record) => record.deviceInfo?.ip || '-',
    },
    {
      title: '设备',
      key: 'device',
      width: 140,
      render: (_, record) => {
        if (!record.deviceInfo?.userAgent) return '-';
        return (
          <Tooltip title={record.deviceInfo.userAgent}>
            <span>{parseUserAgent(record.deviceInfo.userAgent)}</span>
          </Tooltip>
        );
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 160,
      render: (date) => dayjs(date).format('YYYY-MM-DD HH:mm'),
    },
    {
      title: '操作',
      key: 'action',
      width: 80,
      render: (_, record) => <a onClick={() => showConversationDetail(record)}>详情</a>,
    },
  ];

  return (
    <div className="p-6">
      <Title level={4} className="mb-6">对话管理</Title>

      {/* Statistics Cards - Conversations */}
      <Row gutter={[16, 16]} className="mb-4">
        <Col xs={12} sm={6}>
          <Card>
            <Spin spinning={loadingStats}>
              <Statistic
                title="总对话数"
                value={stats?.total ?? 0}
                prefix={<MessageOutlined />}
                valueStyle={{ color: '#1890ff' }}
              />
            </Spin>
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card>
            <Spin spinning={loadingStats}>
              <Statistic
                title="今日对话"
                value={stats?.todayCount ?? 0}
                prefix={<BarChartOutlined />}
                valueStyle={{ color: '#722ed1' }}
              />
            </Spin>
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card>
            <Spin spinning={loadingStats}>
              <Statistic
                title="已转化"
                value={stats?.converted ?? 0}
                prefix={<CheckCircleOutlined />}
                valueStyle={{ color: '#52c41a' }}
              />
              <div className="mt-2 text-gray-500 text-sm">
                转化率: {stats?.conversionRate ?? '0'}%
              </div>
            </Spin>
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card>
            <Spin spinning={loadingStats}>
              <Statistic
                title="进行中"
                value={stats?.active ?? 0}
                prefix={<MessageOutlined />}
                valueStyle={{ color: '#faad14' }}
              />
            </Spin>
          </Card>
        </Col>
      </Row>

      {/* Token Usage Statistics */}
      <Row gutter={[16, 16]} className="mb-4">
        <Col xs={12} sm={6}>
          <Card>
            <Spin spinning={loadingStats}>
              <Statistic
                title="总 Tokens"
                value={stats?.tokenStats?.totalTokens ?? 0}
                prefix={<ThunderboltOutlined />}
                valueStyle={{ color: '#13c2c2', fontSize: 20 }}
                formatter={(value) => formatNumber(value as number)}
              />
              <div className="mt-1 text-xs text-gray-400">
                输入: {formatNumber(stats?.tokenStats?.totalInputTokens ?? 0)} |
                输出: {formatNumber(stats?.tokenStats?.totalOutputTokens ?? 0)}
              </div>
            </Spin>
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card>
            <Spin spinning={loadingStats}>
              <Statistic
                title="总成本"
                value={stats?.tokenStats?.totalEstimatedCost ?? 0}
                prefix={<DollarOutlined />}
                precision={2}
                valueStyle={{ color: '#eb2f96', fontSize: 20 }}
              />
              <div className="mt-1 text-xs text-gray-400">
                API 调用: {formatNumber(stats?.tokenStats?.totalApiCalls ?? 0)} 次
              </div>
            </Spin>
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card>
            <Spin spinning={loadingStats}>
              <Statistic
                title="今日 Tokens"
                value={stats?.todayTokenStats?.totalTokens ?? 0}
                prefix={<ApiOutlined />}
                valueStyle={{ color: '#1890ff', fontSize: 20 }}
                formatter={(value) => formatNumber(value as number)}
              />
              <div className="mt-1 text-xs text-gray-400">
                输入: {formatNumber(stats?.todayTokenStats?.totalInputTokens ?? 0)} |
                输出: {formatNumber(stats?.todayTokenStats?.totalOutputTokens ?? 0)}
              </div>
            </Spin>
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card>
            <Spin spinning={loadingStats}>
              <Statistic
                title="今日成本"
                value={stats?.todayTokenStats?.totalEstimatedCost ?? 0}
                prefix={<DollarOutlined />}
                precision={4}
                valueStyle={{ color: '#fa8c16', fontSize: 20 }}
              />
              <div className="mt-1 text-xs text-gray-400">
                API 调用: {formatNumber(stats?.todayTokenStats?.totalApiCalls ?? 0)} 次
              </div>
            </Spin>
          </Card>
        </Col>
      </Row>

      {/* Filters */}
      <Card className="mb-4">
        <Space wrap>
          <Select
            placeholder="状态"
            allowClear
            value={filters.status}
            onChange={(value) => setFilters((prev) => ({ ...prev, status: value, page: 1 }))}
            style={{ width: 120 }}
            options={[
              { value: 'ACTIVE', label: '进行中' },
              { value: 'ENDED', label: '已结束' },
              { value: 'ARCHIVED', label: '已归档' },
            ]}
          />
          <Select
            placeholder="转化状态"
            allowClear
            value={filters.hasConverted}
            onChange={(value) => setFilters((prev) => ({ ...prev, hasConverted: value, page: 1 }))}
            style={{ width: 120 }}
            options={[
              { value: true, label: '已转化' },
              { value: false, label: '未转化' },
            ]}
          />
          <RangePicker
            value={dateRange}
            onChange={handleDateRangeChange}
            placeholder={['开始日期', '结束日期']}
          />
          <Select
            value={filters.sortBy}
            onChange={(value) => setFilters((prev) => ({ ...prev, sortBy: value }))}
            style={{ width: 120 }}
            options={[
              { value: 'createdAt', label: '创建时间' },
              { value: 'updatedAt', label: '更新时间' },
              { value: 'messageCount', label: '消息数' },
            ]}
          />
          <Select
            value={filters.sortOrder}
            onChange={(value) => setFilters((prev) => ({ ...prev, sortOrder: value }))}
            style={{ width: 100 }}
            options={[
              { value: 'DESC', label: '降序' },
              { value: 'ASC', label: '升序' },
            ]}
          />
        </Space>
      </Card>

      {/* Conversations Table */}
      <Card>
        <Spin spinning={loadingConversations}>
          <Table
            columns={columns}
            dataSource={conversationsData?.items || []}
            rowKey="id"
            pagination={{
              current: conversationsData?.page || 1,
              pageSize: conversationsData?.pageSize || 20,
              total: conversationsData?.total || 0,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条`,
            }}
            onChange={handleTableChange}
            scroll={{ x: 1200 }}
          />
        </Spin>
      </Card>

      {/* Conversation Detail Drawer */}
      <Drawer
        title="对话详情"
        placement="right"
        width={600}
        open={detailDrawerOpen}
        onClose={() => {
          setDetailDrawerOpen(false);
          setSelectedConversationId(null);
        }}
      >
        <Spin spinning={loadingDetail}>
          {conversationDetail && (
            <div>
              {/* Basic Info */}
              <Descriptions bordered column={2} size="small" className="mb-4">
                <Descriptions.Item label="对话ID" span={2}>
                  <code className="text-xs">{conversationDetail.id}</code>
                </Descriptions.Item>
                <Descriptions.Item label="标题" span={2}>
                  {conversationDetail.title || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="用户ID">
                  <code className="text-xs">{conversationDetail.userId.slice(0, 12)}...</code>
                </Descriptions.Item>
                <Descriptions.Item label="状态">
                  <Tag color={STATUS_COLORS[conversationDetail.status]}>
                    {STATUS_LABELS[conversationDetail.status]}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="消息数">
                  {conversationDetail.messageCount}
                </Descriptions.Item>
                <Descriptions.Item label="转化">
                  {conversationDetail.hasConverted ? (
                    <Tag color="green">已转化</Tag>
                  ) : (
                    <Tag>未转化</Tag>
                  )}
                </Descriptions.Item>
                <Descriptions.Item label="创建时间">
                  {dayjs(conversationDetail.createdAt).format('YYYY-MM-DD HH:mm:ss')}
                </Descriptions.Item>
                <Descriptions.Item label="结束时间">
                  {conversationDetail.endedAt
                    ? dayjs(conversationDetail.endedAt).format('YYYY-MM-DD HH:mm:ss')
                    : '-'}
                </Descriptions.Item>
              </Descriptions>

              {/* Device Info */}
              {conversationDetail.deviceInfo && (
                <>
                  <Title level={5}>
                    <Space>
                      <LaptopOutlined />
                      设备信息
                    </Space>
                  </Title>
                  <Descriptions bordered column={1} size="small" className="mb-4">
                    <Descriptions.Item label="访问IP">
                      <Space>
                        <GlobalOutlined />
                        {conversationDetail.deviceInfo.ip || '-'}
                        {conversationDetail.deviceInfo.region && (
                          <Tag>{conversationDetail.deviceInfo.region}</Tag>
                        )}
                      </Space>
                    </Descriptions.Item>
                    <Descriptions.Item label="User-Agent">
                      <Tooltip title={conversationDetail.deviceInfo.userAgent}>
                        <span className="text-xs">
                          {conversationDetail.deviceInfo.userAgent
                            ? parseUserAgent(conversationDetail.deviceInfo.userAgent)
                            : '-'}
                        </span>
                      </Tooltip>
                    </Descriptions.Item>
                    <Descriptions.Item label="设备指纹">
                      <code className="text-xs">
                        {conversationDetail.deviceInfo.fingerprint || '-'}
                      </code>
                    </Descriptions.Item>
                  </Descriptions>
                </>
              )}

              {/* Token Usage */}
              <Title level={5}>
                <Space>
                  <BarChartOutlined />
                  Token 使用
                </Space>
              </Title>
              <Row gutter={[8, 8]} className="mb-4">
                <Col span={8}>
                  <Card size="small">
                    <Statistic
                      title="输入 Tokens"
                      value={conversationDetail.totalInputTokens}
                      valueStyle={{ fontSize: 16 }}
                    />
                  </Card>
                </Col>
                <Col span={8}>
                  <Card size="small">
                    <Statistic
                      title="输出 Tokens"
                      value={conversationDetail.totalOutputTokens}
                      valueStyle={{ fontSize: 16 }}
                    />
                  </Card>
                </Col>
                <Col span={8}>
                  <Card size="small">
                    <Statistic
                      title="API 调用"
                      value={conversationDetail.tokenDetails?.apiCallCount || 0}
                      suffix="次"
                      valueStyle={{ fontSize: 16 }}
                    />
                  </Card>
                </Col>
                {conversationDetail.tokenDetails && (
                  <>
                    <Col span={8}>
                      <Card size="small">
                        <Statistic
                          title="Cache 创建"
                          value={conversationDetail.tokenDetails.cacheCreationTokens}
                          valueStyle={{ fontSize: 14, color: '#faad14' }}
                        />
                      </Card>
                    </Col>
                    <Col span={8}>
                      <Card size="small">
                        <Statistic
                          title="Cache 读取"
                          value={conversationDetail.tokenDetails.cacheReadTokens}
                          valueStyle={{ fontSize: 14, color: '#52c41a' }}
                        />
                      </Card>
                    </Col>
                    <Col span={8}>
                      <Card size="small">
                        <Statistic
                          title="预估成本"
                          value={conversationDetail.tokenDetails.estimatedCost.toFixed(4)}
                          prefix="$"
                          valueStyle={{ fontSize: 14, color: '#1890ff' }}
                        />
                      </Card>
                    </Col>
                  </>
                )}
              </Row>

              {/* Agent Usage */}
              <Title level={5}>
                <Space>
                  <RobotOutlined />
                  Agent 使用详情
                </Space>
              </Title>
              <Spin spinning={loadingAgentExecs}>
                {agentExecutions && agentExecutions.length > 0 ? (
                  <Table
                    size="small"
                    dataSource={agentExecutions}
                    rowKey="id"
                    pagination={false}
                    className="mb-4"
                    columns={[
                      {
                        title: 'Agent',
                        dataIndex: 'agentName',
                        key: 'agentName',
                        render: (_: string, record: AgentExecutionDto) => {
                          const colors: Record<string, string> = {
                            policy_expert: '#1890ff',
                            assessment_expert: '#52c41a',
                            strategist: '#722ed1',
                            objection_handler: '#eb2f96',
                            case_analyst: '#faad14',
                            memory_manager: '#13c2c2',
                          };
                          return (
                            <Tag color={colors[record.agentType] || 'blue'}>
                              {record.agentName}
                            </Tag>
                          );
                        },
                      },
                      {
                        title: '耗时',
                        dataIndex: 'durationMs',
                        key: 'durationMs',
                        render: (ms: number) => `${(ms / 1000).toFixed(2)}s`,
                      },
                      {
                        title: '状态',
                        dataIndex: 'success',
                        key: 'success',
                        render: (success: boolean) =>
                          success
                            ? <Tag color="green">成功</Tag>
                            : <Tag color="red">失败</Tag>,
                      },
                      {
                        title: '时间',
                        dataIndex: 'createdAt',
                        key: 'createdAt',
                        render: (date: string) => dayjs(date).format('HH:mm:ss'),
                      },
                    ]}
                  />
                ) : (
                  <div className="text-gray-400 text-center py-4 mb-4">
                    暂无 Agent 使用记录
                  </div>
                )}
              </Spin>

              {/* Messages */}
              <Title level={5}>
                <Space>
                  <MessageOutlined />
                  对话内容
                </Space>
              </Title>
              <Spin spinning={loadingMessages}>
                <List
                  size="small"
                  dataSource={messages || []}
                  style={{ maxHeight: 400, overflow: 'auto' }}
                  renderItem={(msg: MessageDto) => (
                    <List.Item
                      className={msg.role === 'user' ? 'bg-blue-50' : 'bg-gray-50'}
                      style={{ borderRadius: 4, marginBottom: 8 }}
                    >
                      <div className="w-full px-2">
                        <div className="flex justify-between items-center mb-1">
                          <Tag color={msg.role === 'user' ? 'blue' : 'green'}>
                            {msg.role === 'user' ? '用户' : '助手'}
                          </Tag>
                          <span className="text-xs text-gray-400">
                            {dayjs(msg.createdAt).format('HH:mm:ss')}
                          </span>
                        </div>
                        <div className="text-sm whitespace-pre-wrap">{msg.content}</div>
                      </div>
                    </List.Item>
                  )}
                />
              </Spin>
            </div>
          )}
        </Spin>
      </Drawer>
    </div>
  );
}

// Helper function to parse User-Agent into readable format
function parseUserAgent(ua: string): string {
  if (!ua) return '-';

  let browser = 'Unknown';
  let os = 'Unknown';

  if (ua.includes('Chrome')) browser = 'Chrome';
  else if (ua.includes('Firefox')) browser = 'Firefox';
  else if (ua.includes('Safari')) browser = 'Safari';
  else if (ua.includes('Edge')) browser = 'Edge';

  if (ua.includes('Windows')) os = 'Windows';
  else if (ua.includes('Mac')) os = 'macOS';
  else if (ua.includes('Linux')) os = 'Linux';
  else if (ua.includes('Android')) os = 'Android';
  else if (ua.includes('iPhone') || ua.includes('iPad')) os = 'iOS';

  return `${browser} / ${os}`;
}

// Helper function to format large numbers (e.g., 1234567 -> 1.23M)
function formatNumber(num: number): string {
  if (num >= 1000000) {
    return (num / 1000000).toFixed(2) + 'M';
  }
  if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'K';
  }
  return num.toString();
}
