import {
  useState,
  useEffect,
  Card,
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  InputNumber,
  Select,
  Tag,
  Tooltip,
  Row,
  Col,
  Statistic,
  message,
  Badge,
  Progress,
  Descriptions,
  DatePicker,
  Tabs,
  List,
  Avatar,
  Divider,
  UserOutlined,
  DollarOutlined,
  TrophyOutlined,
  CrownOutlined,
  GiftOutlined,
  FireOutlined,
  StarOutlined,
  WalletOutlined,
  ShoppingCartOutlined,
  ClockCircleOutlined,
  RiseOutlined,
  Option,
  RangePicker,
  FC,
} from '@/imports';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import { userAssetDataSource, UserAsset, MemberLevel } from '@/services/userAssetDataSource';

interface AssetStatistics {
  totalUsers: number;
  totalPoints: number;
  totalSpent: number;
  levelDistribution: Record<MemberLevel, number>;
}

const LEVEL_COLORS: Record<MemberLevel, string> = {
  BRONZE: '#cd7f32',
  SILVER: '#c0c0c0',
  GOLD: '#ffd700',
  PLATINUM: '#e5e4e2',
  DIAMOND: '#b9f2ff',
};

const LEVEL_NAMES: Record<MemberLevel, string> = {
  BRONZE: '青铜会员',
  SILVER: '白银会员',
  GOLD: '黄金会员',
  PLATINUM: '铂金会员',
  DIAMOND: '钻石会员',
};

const LEVEL_ICONS: Record<MemberLevel, React.ReactNode> = {
  BRONZE: <StarOutlined />,
  SILVER: <StarOutlined />,
  GOLD: <CrownOutlined />,
  PLATINUM: <CrownOutlined />,
  DIAMOND: <CrownOutlined />,
};

const MOCK_USER_ASSETS: UserAsset[] = [
  {
    id: 'UA001',
    tenantId: 'T001',
    userId: 'U001',
    userName: '张三',
    email: 'zhangsan@example.com',
    memberLevel: 'GOLD',
    points: 5680,
    totalSpent: 12580.50,
    availableBalance: 125.80,
    frozenBalance: 0,
    totalOrders: 28,
    joinDate: '2025-06-15',
    lastActiveDate: '2026-03-18',
    status: 'ACTIVE',
  },
  {
    id: 'UA002',
    tenantId: 'T001',
    userId: 'U002',
    userName: '李四',
    email: 'lisi@example.com',
    memberLevel: 'SILVER',
    points: 2300,
    totalSpent: 5620.00,
    availableBalance: 56.20,
    frozenBalance: 0,
    totalOrders: 15,
    joinDate: '2025-08-20',
    lastActiveDate: '2026-03-17',
    status: 'ACTIVE',
  },
  {
    id: 'UA003',
    tenantId: 'T001',
    userId: 'U003',
    userName: '王五',
    email: 'wangwu@example.com',
    memberLevel: 'DIAMOND',
    points: 15800,
    totalSpent: 35680.00,
    availableBalance: 356.80,
    frozenBalance: 0,
    totalOrders: 52,
    joinDate: '2024-12-01',
    lastActiveDate: '2026-03-18',
    status: 'ACTIVE',
  },
  {
    id: 'UA004',
    tenantId: 'T001',
    userId: 'U004',
    userName: '赵六',
    email: 'zhaoliu@example.com',
    memberLevel: 'BRONZE',
    points: 850,
    totalSpent: 1850.00,
    availableBalance: 18.50,
    frozenBalance: 0,
    totalOrders: 6,
    joinDate: '2026-01-10',
    lastActiveDate: '2026-03-15',
    status: 'ACTIVE',
  },
];

const MOCK_STATISTICS: AssetStatistics = {
  totalUsers: 1256,
  totalPoints: 2856000,
  totalSpent: 5689250.00,
  levelDistribution: {
    BRONZE: 580,
    SILVER: 420,
    GOLD: 180,
    PLATINUM: 60,
    DIAMOND: 16,
  },
};

const UserAssets: FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [userAssets, setUserAssets] = useState<UserAsset[]>(MOCK_USER_ASSETS);
  const [statistics, setStatistics] = useState<AssetStatistics>(MOCK_STATISTICS);
  const [selectedUser, setSelectedUser] = useState<UserAsset | null>(null);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [searchParams, setSearchParams] = useState({
    keyword: '',
    memberLevel: undefined as MemberLevel | undefined,
  });

  useEffect(() => {
    loadUserAssets();
  }, []);

  const loadUserAssets = async () => {
    setLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 500));
      setUserAssets(MOCK_USER_ASSETS);
      setStatistics(MOCK_STATISTICS);
    } catch (error) {
      message.error('加载用户资产数据失败');
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = () => {
    let filtered = [...MOCK_USER_ASSETS];
    
    if (searchParams.keyword) {
      filtered = filtered.filter(
        u => u.userName.includes(searchParams.keyword) || 
             u.email.includes(searchParams.keyword) ||
             u.userId.includes(searchParams.keyword)
      );
    }
    
    if (searchParams.memberLevel) {
      filtered = filtered.filter(u => u.memberLevel === searchParams.memberLevel);
    }
    
    setUserAssets(filtered);
  };

  const handleReset = () => {
    setSearchParams({ keyword: '', memberLevel: undefined });
    setUserAssets(MOCK_USER_ASSETS);
  };

  const showUserDetail = (user: UserAsset) => {
    setSelectedUser(user);
    setDetailModalVisible(true);
  };

  const columns: ColumnsType<UserAsset> = [
    {
      title: '用户信息',
      key: 'userInfo',
      width: 200,
      render: (_, record) => (
        <Space>
          <Avatar icon={<UserOutlined />} style={{ backgroundColor: LEVEL_COLORS[record.memberLevel] }} />
          <div>
            <div style={{ fontWeight: 500 }}>{record.userName}</div>
            <div style={{ fontSize: 12, color: '#999' }}>{record.email}</div>
          </div>
        </Space>
      ),
    },
    {
      title: '会员等级',
      dataIndex: 'memberLevel',
      key: 'memberLevel',
      width: 120,
      render: (level: MemberLevel) => (
        <Tag color={LEVEL_COLORS[level]} icon={LEVEL_ICONS[level]}>
          {LEVEL_NAMES[level]}
        </Tag>
      ),
      filters: Object.entries(LEVEL_NAMES).map(([key, name]) => ({
        text: name,
        value: key,
      })),
      onFilter: (value, record) => record.memberLevel === value,
    },
    {
      title: '积分',
      dataIndex: 'points',
      key: 'points',
      width: 120,
      align: 'right',
      render: (points: number) => (
        <span style={{ color: '#1890ff', fontWeight: 500 }}>
          {points.toLocaleString()}
        </span>
      ),
      sorter: (a, b) => a.points - b.points,
    },
    {
      title: '冻结余额',
      dataIndex: 'frozenBalance',
      key: 'frozenBalance',
      width: 100,
      align: 'right',
      render: (balance: number) => (
        <span style={{ color: '#999' }}>¥{balance.toFixed(2)}</span>
      ),
    },
    {
      title: '累计消费',
      dataIndex: 'totalSpent',
      key: 'totalSpent',
      width: 130,
      align: 'right',
      render: (spent: number) => (
        <span style={{ color: '#52c41a' }}>
          ¥{spent.toLocaleString('zh-CN', { minimumFractionDigits: 2 })}
        </span>
      ),
      sorter: (a, b) => a.totalSpent - b.totalSpent,
    },
    {
      title: '订单数',
      dataIndex: 'totalOrders',
      key: 'totalOrders',
      width: 90,
      align: 'center',
      render: (orders: number) => (
        <Badge count={orders} showZero style={{ backgroundColor: '#1890ff' }} />
      ),
      sorter: (a, b) => a.totalOrders - b.totalOrders,
    },
    {
      title: '可用余额',
      dataIndex: 'availableBalance',
      key: 'availableBalance',
      width: 110,
      align: 'right',
      render: (balance: number) => (
        <span style={{ color: '#faad14' }}>
          ¥{balance.toFixed(2)}
        </span>
      ),
    },
    {
      title: '最后活跃',
      dataIndex: 'lastActiveDate',
      key: 'lastActiveDate',
      width: 160,
      render: (time: string) => (
        <Tooltip title={time}>
          <span><ClockCircleOutlined /> {dayjs(time).format('MM-DD')}</span>
        </Tooltip>
      ),
      sorter: (a, b) => new Date(a.lastActiveDate).getTime() - new Date(b.lastActiveDate).getTime(),
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      fixed: 'right',
      render: (_, record) => (
        <Space>
          <Button type="link" size="small" onClick={() => showUserDetail(record)}>
            详情
          </Button>
        </Space>
      ),
    },
  ];

  const renderStatistics = () => (
    <Row gutter={16}>
      <Col span={4}>
        <Card>
          <Statistic
            title="总用户数"
            value={statistics.totalUsers}
            prefix={<UserOutlined />}
            valueStyle={{ color: '#1890ff' }}
          />
        </Card>
      </Col>
      <Col span={4}>
        <Card>
          <Statistic
            title="总积分"
            value={statistics.totalPoints}
            prefix={<StarOutlined />}
            valueStyle={{ color: '#722ed1' }}
          />
        </Card>
      </Col>
      <Col span={4}>
        <Card>
          <Statistic
            title="累计消费"
            value={statistics.totalSpent}
            precision={2}
            prefix={<DollarOutlined />}
            valueStyle={{ color: '#52c41a' }}
          />
        </Card>
      </Col>
      <Col span={12}>
        <Card title="会员等级分布">
          <Row gutter={8}>
            {Object.entries(statistics.levelDistribution).map(([level, count]) => (
              <Col span={4} key={level}>
                <div style={{ textAlign: 'center' }}>
                  <Tag color={LEVEL_COLORS[level as MemberLevel]} style={{ marginBottom: 4 }}>
                    {LEVEL_NAMES[level as MemberLevel]}
                  </Tag>
                  <div style={{ fontWeight: 500 }}>{count}</div>
                  <Progress 
                    percent={Math.round((count / statistics.totalUsers) * 100)} 
                    size="small" 
                    showInfo={false}
                    strokeColor={LEVEL_COLORS[level as MemberLevel]}
                  />
                </div>
              </Col>
            ))}
          </Row>
        </Card>
      </Col>
    </Row>
  );

  const renderUserDetail = () => {
    if (!selectedUser) return null;

    return (
      <Modal
        title="用户资产详情"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={null}
        width={800}
      >
        <Tabs 
          defaultActiveKey="overview"
          items={[
            { key: 'overview', label: '资产概览', children: (
              <>
                <Descriptions bordered column={2}>
                  <Descriptions.Item label="用户ID">{selectedUser.userId}</Descriptions.Item>
                  <Descriptions.Item label="用户名">{selectedUser.userName}</Descriptions.Item>
                  <Descriptions.Item label="邮箱">{selectedUser.email}</Descriptions.Item>
                  <Descriptions.Item label="会员等级">
                    <Tag color={LEVEL_COLORS[selectedUser.memberLevel]} icon={LEVEL_ICONS[selectedUser.memberLevel]}>
                      {LEVEL_NAMES[selectedUser.memberLevel]}
                    </Tag>
                  </Descriptions.Item>
                  <Descriptions.Item label="积分">{selectedUser.points.toLocaleString()}</Descriptions.Item>
                  <Descriptions.Item label="状态">
                    <Tag color={selectedUser.status === 'ACTIVE' ? 'green' : selectedUser.status === 'INACTIVE' ? 'gray' : 'red'}>
                      {selectedUser.status === 'ACTIVE' ? '活跃' : selectedUser.status === 'INACTIVE' ? '非活跃' : '暂停'}
                    </Tag>
                  </Descriptions.Item>
                </Descriptions>

                <Divider />

                <Row gutter={16}>
                  <Col span={6}>
                    <Statistic
                      title="可用余额"
                      value={selectedUser.availableBalance}
                      precision={2}
                      prefix="¥"
                      valueStyle={{ color: '#1890ff' }}
                    />
                  </Col>
                  <Col span={6}>
                    <Statistic
                      title="冻结余额"
                      value={selectedUser.frozenBalance}
                      precision={2}
                      prefix="¥"
                      valueStyle={{ color: '#999' }}
                    />
                  </Col>
                  <Col span={6}>
                    <Statistic
                      title="累计消费"
                      value={selectedUser.totalSpent}
                      precision={2}
                      prefix="¥"
                      valueStyle={{ color: '#52c41a' }}
                    />
                  </Col>
                  <Col span={6}>
                    <Statistic
                      title="订单数"
                      value={selectedUser.totalOrders}
                      prefix={<ShoppingCartOutlined />}
                    />
                  </Col>
                </Row>
              </>
            )},
            { key: 'spending', label: '消费统计', children: (
              <Row gutter={16}>
                <Col span={12}>
                  <Card>
                    <Statistic
                      title="总订单数"
                      value={selectedUser.totalOrders}
                      prefix={<ShoppingCartOutlined />}
                    />
                  </Card>
                </Col>
                <Col span={12}>
                  <Card>
                    <Statistic
                      title="客单价"
                      value={selectedUser.totalSpent / selectedUser.totalOrders}
                      precision={2}
                      prefix="¥"
                    />
                  </Card>
                </Col>
              </Row>
            )},
          ]}
        />
      </Modal>
    );
  };

  return (
    <div style={{ padding: 24 }}>
      <Card title="用户资产管理" style={{ marginBottom: 16 }}>
        {renderStatistics()}
      </Card>

      <Card>
        <Row gutter={16} style={{ marginBottom: 16 }}>
          <Col span={6}>
            <Input
              placeholder="搜索用户名/邮箱/ID"
              value={searchParams.keyword}
              onChange={e => setSearchParams({ ...searchParams, keyword: e.target.value })}
              onPressEnter={handleSearch}
            />
          </Col>
          <Col span={4}>
            <Select
              placeholder="会员等级"
              value={searchParams.memberLevel}
              onChange={value => setSearchParams({ ...searchParams, memberLevel: value })}
              allowClear
              style={{ width: '100%' }}
            >
              {Object.entries(LEVEL_NAMES).map(([key, name]) => (
                <Option key={key} value={key}>
                  <Tag color={LEVEL_COLORS[key as MemberLevel]}>{name}</Tag>
                </Option>
              ))}
            </Select>
          </Col>
          <Col span={4}>
            <Space>
              <Button type="primary" onClick={handleSearch}>搜索</Button>
              <Button onClick={handleReset}>重置</Button>
            </Space>
          </Col>
        </Row>

        <Table
          columns={columns}
          dataSource={userAssets}
          rowKey="id"
          loading={loading}
          scroll={{ x: 1400 }}
          pagination={{
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
          }}
        />
      </Card>

      {renderUserDetail()}
    </div>
  );
};

export default UserAssets;
