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

const { Option } = Select;
const { RangePicker } = DatePicker;
const { TabPane } = Tabs;

interface UserAsset {
  shopId: string;
  userId: string;
  userName: string;
  userEmail: string;
  totalPoints: number;
  availablePoints: number;
  frozenPoints: number;
  totalSpent: number;
  totalOrders: number;
  memberLevel: MemberLevel;
  memberScore: number;
  cashbackBalance: number;
  couponCount: number;
  lastActiveAt: string;
  createdAt: string;
}

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',
    shopId: 'S001',
    userId: 'U001',
    userName: '张三',
    userEmail: 'zhangsan@example.com',
    totalPoints: 5680,
    availablePoints: 5200,
    frozenPoints: 480,
    totalSpent: 12580.50,
    totalOrders: 28,
    memberLevel: 'GOLD',
    memberScore: 12580,
    cashbackBalance: 125.80,
    couponCount: 5,
    lastActiveAt: '2026-03-18 14:30:00',
    createdAt: '2025-06-15 10:00:00',
  },
  {
    id: 'UA002',
    tenantId: 'T001',
    shopId: 'S001',
    userId: 'U002',
    userName: '李四',
    userEmail: 'lisi@example.com',
    totalPoints: 2300,
    availablePoints: 2100,
    frozenPoints: 200,
    totalSpent: 5620.00,
    totalOrders: 15,
    memberLevel: 'SILVER',
    memberScore: 5620,
    cashbackBalance: 56.20,
    couponCount: 3,
    lastActiveAt: '2026-03-17 09:15:00',
    createdAt: '2025-08-20 14:30:00',
  },
  {
    id: 'UA003',
    tenantId: 'T001',
    shopId: 'S001',
    userId: 'U003',
    userName: '王五',
    userEmail: 'wangwu@example.com',
    totalPoints: 15800,
    availablePoints: 15000,
    frozenPoints: 800,
    totalSpent: 35680.00,
    totalOrders: 52,
    memberLevel: 'DIAMOND',
    memberScore: 35680,
    cashbackBalance: 356.80,
    couponCount: 12,
    lastActiveAt: '2026-03-18 16:45:00',
    createdAt: '2024-12-01 08:00:00',
  },
  {
    id: 'UA004',
    tenantId: 'T001',
    shopId: 'S001',
    userId: 'U004',
    userName: '赵六',
    userEmail: 'zhaoliu@example.com',
    totalPoints: 850,
    availablePoints: 800,
    frozenPoints: 50,
    totalSpent: 1850.00,
    totalOrders: 6,
    memberLevel: 'BRONZE',
    memberScore: 1850,
    cashbackBalance: 18.50,
    couponCount: 1,
    lastActiveAt: '2026-03-15 11:20:00',
    createdAt: '2026-01-10 16:00:00',
  },
];

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

export const UserAssets: React.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.userEmail.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.userEmail}</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: 'availablePoints',
      key: 'availablePoints',
      width: 120,
      align: 'right',
      render: (points: number) => (
        <span style={{ color: '#1890ff', fontWeight: 500 }}>
          {points.toLocaleString()}
        </span>
      ),
      sorter: (a, b) => a.availablePoints - b.availablePoints,
    },
    {
      title: '冻结积分',
      dataIndex: 'frozenPoints',
      key: 'frozenPoints',
      width: 100,
      align: 'right',
      render: (points: number) => (
        <span style={{ color: '#999' }}>{points.toLocaleString()}</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: 'cashbackBalance',
      key: 'cashbackBalance',
      width: 110,
      align: 'right',
      render: (balance: number) => (
        <span style={{ color: '#faad14' }}>
          ¥{balance.toFixed(2)}
        </span>
      ),
    },
    {
      title: '优惠券',
      dataIndex: 'couponCount',
      key: 'couponCount',
      width: 80,
      align: 'center',
      render: (count: number) => (
        <Tag color="orange" icon={<GiftOutlined />}>{count}</Tag>
      ),
    },
    {
      title: '最后活跃',
      dataIndex: 'lastActiveAt',
      key: 'lastActiveAt',
      width: 160,
      render: (time: string) => (
        <Tooltip title={time}>
          <span><ClockCircleOutlined /> {dayjs(time).format('MM-DD HH:mm')}</span>
        </Tooltip>
      ),
      sorter: (a, b) => new Date(a.lastActiveAt).getTime() - new Date(b.lastActiveAt).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;

    const nextLevelThresholds: Record<MemberLevel, number> = {
      BRONZE: 1000,
      SILVER: 5000,
      GOLD: 20000,
      PLATINUM: 100000,
      DIAMOND: Infinity,
    };

    const currentThreshold = nextLevelThresholds[selectedUser.memberLevel];
    const progress = selectedUser.memberLevel === 'DIAMOND' 
      ? 100 
      : Math.min((selectedUser.memberScore / currentThreshold) * 100, 100);

    return (
      <Modal
        title="用户资产详情"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={null}
        width={800}
      >
        <Tabs defaultActiveKey="overview">
          <TabPane tab="资产概览" key="overview">
            <Descriptions bordered column={2}>
              <Descriptions.Item label="用户ID">{selectedUser.userId}</Descriptions.Item>
              <Descriptions.Item label="用户名">{selectedUser.userName}</Descriptions.Item>
              <Descriptions.Item label="邮箱">{selectedUser.userEmail}</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.memberScore.toLocaleString()}</Descriptions.Item>
              <Descriptions.Item label="升级进度">
                <Progress 
                  percent={progress} 
                  size="small" 
                  format={() => `${selectedUser.memberScore.toLocaleString()} / ${currentThreshold.toLocaleString()}`}
                />
              </Descriptions.Item>
            </Descriptions>

            <Divider />

            <Row gutter={16}>
              <Col span={6}>
                <Statistic
                  title="可用积分"
                  value={selectedUser.availablePoints}
                  prefix={<StarOutlined />}
                  valueStyle={{ color: '#1890ff' }}
                />
              </Col>
              <Col span={6}>
                <Statistic
                  title="冻结积分"
                  value={selectedUser.frozenPoints}
                  prefix={<StarOutlined />}
                  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.cashbackBalance}
                  precision={2}
                  prefix="¥"
                  valueStyle={{ color: '#faad14' }}
                />
              </Col>
            </Row>
          </TabPane>
          <TabPane tab="消费统计" key="spending">
            <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>
          </TabPane>
          <TabPane tab="优惠券" key="coupons">
            <List
              dataSource={Array(selectedUser.couponCount).fill(null).map((_, i) => ({
                id: `CPN${i + 1}`,
                name: `优惠券 ${i + 1}`,
                value: Math.floor(Math.random() * 50) + 10,
                minSpend: 100,
                expireAt: dayjs().add(30, 'days').format('YYYY-MM-DD'),
              }))}
              renderItem={(item: any) => (
                <List.Item>
                  <List.Item.Meta
                    avatar={<Avatar style={{ backgroundColor: '#faad14' }} icon={<GiftOutlined />} />}
                    title={item.name}
                    description={`满${item.minSpend}减${item.value} | 有效期至 ${item.expireAt}`}
                  />
                </List.Item>
              )}
            />
          </TabPane>
        </Tabs>
      </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;
