import { useState } from 'react';
import {
  Card,
  Table,
  Tag,
  Space,
  Select,
  Input,
  Row,
  Col,
  Statistic,
  Typography,
  Drawer,
  Descriptions,
  Spin,
  Avatar,
  Divider,
  List,
  Tooltip,
} from 'antd';
import {
  UserOutlined,
  TeamOutlined,
  UserAddOutlined,
  SearchOutlined,
  MessageOutlined,
  GlobalOutlined,
  LaptopOutlined,
  CheckCircleOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import {
  useUsers,
  useUserStatistics,
  useUserDetail,
  type UserDto,
  type UserType,
} from '../../application';
import { useUserConversations, type ConversationListItem } from '../../../conversations/application';

const { Title } = Typography;
const { Search } = Input;

const TYPE_COLORS: Record<UserType, string> = {
  ANONYMOUS: 'default',
  REGISTERED: 'green',
};

const TYPE_LABELS: Record<UserType, string> = {
  ANONYMOUS: '匿名用户',
  REGISTERED: '注册用户',
};

export function UsersPage() {
  const [filters, setFilters] = useState<{
    type?: UserType;
    phone?: string;
    nickname?: string;
    page: number;
    pageSize: number;
    sortBy: 'createdAt' | 'lastActiveAt';
    sortOrder: 'ASC' | 'DESC';
  }>({
    page: 1,
    pageSize: 20,
    sortBy: 'createdAt',
    sortOrder: 'DESC',
  });

  const [searchKeyword, setSearchKeyword] = useState('');
  const [detailDrawerOpen, setDetailDrawerOpen] = useState(false);
  const [selectedUserId, setSelectedUserId] = useState<string | null>(null);

  // Queries
  const { data: usersData, isLoading: loadingUsers } = useUsers(filters);
  const { data: stats, isLoading: loadingStats } = useUserStatistics();
  const { data: userDetail, isLoading: loadingDetail } = useUserDetail(
    selectedUserId || '',
    !!selectedUserId && detailDrawerOpen
  );
  const { data: userConversations, isLoading: loadingConversations } = useUserConversations(
    selectedUserId || '',
    10,
    !!selectedUserId && detailDrawerOpen
  );

  const showUserDetail = (user: UserDto) => {
    setSelectedUserId(user.id);
    setDetailDrawerOpen(true);
  };

  const handleSearch = (value: string) => {
    setSearchKeyword(value);
    if (value.length >= 2) {
      // Search by phone or nickname
      if (/^\d+$/.test(value)) {
        setFilters((prev) => ({ ...prev, phone: value, nickname: undefined, page: 1 }));
      } else {
        setFilters((prev) => ({ ...prev, nickname: value, phone: undefined, page: 1 }));
      }
    } else if (value === '') {
      setFilters((prev) => ({ ...prev, phone: undefined, nickname: undefined, page: 1 }));
    }
  };

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

  const columns: ColumnsType<UserDto> = [
    {
      title: '用户',
      key: 'user',
      render: (_, record) => (
        <Space>
          <Avatar
            size="small"
            src={record.avatar}
            icon={<UserOutlined />}
          />
          <span>{record.nickname || record.phone || record.id.slice(0, 8)}</span>
        </Space>
      ),
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: 100,
      render: (type: UserType) => (
        <Tag color={TYPE_COLORS[type]}>{TYPE_LABELS[type]}</Tag>
      ),
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
      width: 140,
      render: (phone) => phone || '-',
    },
    {
      title: '注册时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
      render: (date) => dayjs(date).format('YYYY-MM-DD HH:mm'),
    },
    {
      title: '最后活跃',
      dataIndex: 'lastActiveAt',
      key: 'lastActiveAt',
      width: 180,
      render: (date) => dayjs(date).format('YYYY-MM-DD HH:mm'),
    },
    {
      title: '操作',
      key: 'action',
      width: 80,
      render: (_, record) => (
        <a onClick={() => showUserDetail(record)}>详情</a>
      ),
    },
  ];

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

      {/* Statistics Cards */}
      <Row gutter={[16, 16]} className="mb-4">
        <Col xs={24} sm={8}>
          <Card>
            <Spin spinning={loadingStats}>
              <Statistic
                title="总用户数"
                value={stats?.total ?? 0}
                prefix={<TeamOutlined />}
                valueStyle={{ color: '#1890ff' }}
              />
            </Spin>
          </Card>
        </Col>
        <Col xs={24} sm={8}>
          <Card>
            <Spin spinning={loadingStats}>
              <Statistic
                title="注册用户"
                value={stats?.registered ?? 0}
                prefix={<UserAddOutlined />}
                valueStyle={{ color: '#52c41a' }}
              />
              <div className="mt-2 text-gray-500 text-sm">
                注册率: {stats?.registrationRate ?? '0'}%
              </div>
            </Spin>
          </Card>
        </Col>
        <Col xs={24} sm={8}>
          <Card>
            <Spin spinning={loadingStats}>
              <Statistic
                title="匿名用户"
                value={stats?.anonymous ?? 0}
                prefix={<UserOutlined />}
                valueStyle={{ color: '#8c8c8c' }}
              />
            </Spin>
          </Card>
        </Col>
      </Row>

      {/* Filters */}
      <Card className="mb-4">
        <Space wrap>
          <Search
            placeholder="搜索手机号或昵称"
            allowClear
            value={searchKeyword}
            onChange={(e) => setSearchKeyword(e.target.value)}
            onSearch={handleSearch}
            style={{ width: 220 }}
            prefix={<SearchOutlined />}
          />
          <Select
            placeholder="用户类型"
            allowClear
            value={filters.type}
            onChange={(value) => setFilters((prev) => ({ ...prev, type: value, page: 1 }))}
            style={{ width: 120 }}
            options={[
              { value: 'REGISTERED', label: '注册用户' },
              { value: 'ANONYMOUS', label: '匿名用户' },
            ]}
          />
          <Select
            value={filters.sortBy}
            onChange={(value) => setFilters((prev) => ({ ...prev, sortBy: value }))}
            style={{ width: 120 }}
            options={[
              { value: 'createdAt', label: '注册时间' },
              { value: 'lastActiveAt', label: '活跃时间' },
            ]}
          />
          <Select
            value={filters.sortOrder}
            onChange={(value) => setFilters((prev) => ({ ...prev, sortOrder: value }))}
            style={{ width: 100 }}
            options={[
              { value: 'DESC', label: '降序' },
              { value: 'ASC', label: '升序' },
            ]}
          />
        </Space>
      </Card>

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

      {/* User Detail Drawer */}
      <Drawer
        title="用户详情"
        placement="right"
        width={520}
        open={detailDrawerOpen}
        onClose={() => {
          setDetailDrawerOpen(false);
          setSelectedUserId(null);
        }}
      >
        <Spin spinning={loadingDetail}>
          {userDetail && (
            <div>
              <div className="text-center mb-6">
                <Avatar
                  size={80}
                  src={userDetail.avatar}
                  icon={<UserOutlined />}
                />
                <div className="mt-3">
                  <Tag color={TYPE_COLORS[userDetail.type]}>
                    {TYPE_LABELS[userDetail.type]}
                  </Tag>
                </div>
              </div>

              <Descriptions bordered column={1} size="small">
                <Descriptions.Item label="用户ID">
                  <code className="text-xs">{userDetail.id}</code>
                </Descriptions.Item>
                <Descriptions.Item label="昵称">
                  {userDetail.nickname || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="手机号">
                  {userDetail.phone || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="设备指纹">
                  <code className="text-xs">
                    {userDetail.fingerprint?.slice(0, 16) || '-'}...
                  </code>
                </Descriptions.Item>
                <Descriptions.Item label="注册时间">
                  {dayjs(userDetail.createdAt).format('YYYY-MM-DD HH:mm:ss')}
                </Descriptions.Item>
                <Descriptions.Item label="更新时间">
                  {userDetail.updatedAt
                    ? dayjs(userDetail.updatedAt).format('YYYY-MM-DD HH:mm:ss')
                    : '-'}
                </Descriptions.Item>
                <Descriptions.Item label="最后活跃">
                  {dayjs(userDetail.lastActiveAt).format('YYYY-MM-DD HH:mm:ss')}
                </Descriptions.Item>
              </Descriptions>

              {/* Recent Conversations */}
              <Divider orientation="left">
                <Space>
                  <MessageOutlined />
                  最近咨询记录
                </Space>
              </Divider>

              <Spin spinning={loadingConversations}>
                {userConversations && userConversations.length > 0 ? (
                  <List
                    size="small"
                    dataSource={userConversations}
                    renderItem={(conv: ConversationListItem) => (
                      <List.Item>
                        <div className="w-full">
                          <div className="flex justify-between items-start mb-2">
                            <div className="flex-1 min-w-0">
                              <div className="font-medium truncate">
                                {conv.title || '未命名对话'}
                              </div>
                              <div className="text-xs text-gray-500">
                                {dayjs(conv.createdAt).format('YYYY-MM-DD HH:mm')}
                              </div>
                            </div>
                            <Space size={4}>
                              <Tag color={conv.status === 'ACTIVE' ? 'green' : 'default'}>
                                {conv.status === 'ACTIVE' ? '进行中' : '已结束'}
                              </Tag>
                              {conv.hasConverted && (
                                <Tooltip title="已转化">
                                  <CheckCircleOutlined style={{ color: '#52c41a' }} />
                                </Tooltip>
                              )}
                            </Space>
                          </div>

                          {/* Device Info */}
                          {conv.deviceInfo && (
                            <div className="text-xs text-gray-400 space-y-1">
                              {conv.deviceInfo.ip && (
                                <div className="flex items-center gap-1">
                                  <GlobalOutlined />
                                  <span>IP: {conv.deviceInfo.ip}</span>
                                  {conv.deviceInfo.region && (
                                    <span className="text-gray-300">({conv.deviceInfo.region})</span>
                                  )}
                                </div>
                              )}
                              {conv.deviceInfo.userAgent && (
                                <Tooltip title={conv.deviceInfo.userAgent}>
                                  <div className="flex items-center gap-1 truncate">
                                    <LaptopOutlined />
                                    <span className="truncate">{parseUserAgent(conv.deviceInfo.userAgent)}</span>
                                  </div>
                                </Tooltip>
                              )}
                              {conv.deviceInfo.fingerprint && (
                                <div className="flex items-center gap-1">
                                  <span>指纹: </span>
                                  <code className="text-xs">{conv.deviceInfo.fingerprint.slice(0, 12)}...</code>
                                </div>
                              )}
                            </div>
                          )}

                          <div className="text-xs text-gray-500 mt-1">
                            消息数: {conv.messageCount}
                          </div>
                        </div>
                      </List.Item>
                    )}
                  />
                ) : (
                  <div className="text-center text-gray-400 py-4">暂无咨询记录</div>
                )}
              </Spin>
            </div>
          )}
        </Spin>
      </Drawer>
    </div>
  );
}

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

  // Simple parsing - extract browser and OS
  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}`;
}
