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,
  Divider,
  Alert,
  Switch,
  Slider,
  List,
  Avatar,
  Timeline,
} from 'antd';
import {
  CrownOutlined,
  StarOutlined,
  TrophyOutlined,
  EditOutlined,
  PlusOutlined,
  DeleteOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  SettingOutlined,
  GiftOutlined,
  DollarOutlined,
  PercentageOutlined,
  ThunderboltOutlined,
  RiseOutlined,
  UserOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import { userAssetDataSource, MemberLevelConfig, MemberLevel as MemberLevelType } from '@/services/userAssetDataSource';

const { Option } = Select;

type MemberLevel = 'BRONZE' | 'SILVER' | 'GOLD' | 'PLATINUM' | 'DIAMOND';

interface MemberLevelRule {
  id: string;
  tenantId: string;
  level: MemberLevel;
  levelName: string;
  minScore: number;
  maxScore: number;
  discount: number;
  pointsMultiplier: number;
  benefits: string[];
  isActive: boolean;
  createdAt: string;
  updatedAt: string;
}

interface MemberStatistics {
  totalMembers: number;
  levelDistribution: Record<MemberLevel, number>;
  upgradeCount: number;
  downgradeCount: number;
  avgMemberScore: number;
}

interface LevelChangeLog {
  id: string;
  userId: string;
  userName: string;
  oldLevel: MemberLevel;
  newLevel: MemberLevel;
  reason: string;
  changedAt: string;
}

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_LEVEL_RULES: MemberLevelRule[] = [
  {
    id: 'LR001',
    tenantId: 'T001',
    level: 'BRONZE',
    levelName: '青铜会员',
    minScore: 0,
    maxScore: 999,
    discount: 1.00,
    pointsMultiplier: 1.0,
    benefits: ['生日优惠', '积分兑换'],
    isActive: true,
    createdAt: '2025-01-01 00:00:00',
    updatedAt: '2025-01-01 00:00:00',
  },
  {
    id: 'LR002',
    tenantId: 'T001',
    level: 'SILVER',
    levelName: '白银会员',
    minScore: 1000,
    maxScore: 4999,
    discount: 0.98,
    pointsMultiplier: 1.1,
    benefits: ['生日优惠', '积分兑换', '专属客服', '优先发货'],
    isActive: true,
    createdAt: '2025-01-01 00:00:00',
    updatedAt: '2025-01-01 00:00:00',
  },
  {
    id: 'LR003',
    tenantId: 'T001',
    level: 'GOLD',
    levelName: '黄金会员',
    minScore: 5000,
    maxScore: 19999,
    discount: 0.95,
    pointsMultiplier: 1.2,
    benefits: ['生日优惠', '积分兑换', '专属客服', '优先发货', '专属折扣', '免费退换'],
    isActive: true,
    createdAt: '2025-01-01 00:00:00',
    updatedAt: '2025-01-01 00:00:00',
  },
  {
    id: 'LR004',
    tenantId: 'T001',
    level: 'PLATINUM',
    levelName: '铂金会员',
    minScore: 20000,
    maxScore: 99999,
    discount: 0.90,
    pointsMultiplier: 1.3,
    benefits: ['生日优惠', '积分兑换', '专属客服', '优先发货', '专属折扣', '免费退换', 'VIP活动', '专属礼品'],
    isActive: true,
    createdAt: '2025-01-01 00:00:00',
    updatedAt: '2025-01-01 00:00:00',
  },
  {
    id: 'LR005',
    tenantId: 'T001',
    level: 'DIAMOND',
    levelName: '钻石会员',
    minScore: 100000,
    maxScore: 999999999,
    discount: 0.85,
    pointsMultiplier: 1.5,
    benefits: ['生日优惠', '积分兑换', '专属客服', '优先发货', '专属折扣', '免费退换', 'VIP活动', '专属礼品', '私人定制', '年度礼包'],
    isActive: true,
    createdAt: '2025-01-01 00:00:00',
    updatedAt: '2025-01-01 00:00:00',
  },
];

const MOCK_STATISTICS: MemberStatistics = {
  totalMembers: 1256,
  levelDistribution: {
    BRONZE: 580,
    SILVER: 420,
    GOLD: 180,
    PLATINUM: 60,
    DIAMOND: 16,
  },
  upgradeCount: 45,
  downgradeCount: 8,
  avgMemberScore: 4580,
};

const MOCK_CHANGE_LOGS: LevelChangeLog[] = [
  {
    id: 'CL001',
    userId: 'U001',
    userName: '张三',
    oldLevel: 'SILVER',
    newLevel: 'GOLD',
    reason: '消费积分达标自动升级',
    changedAt: '2026-03-18 14:30:00',
  },
  {
    id: 'CL002',
    userId: 'U005',
    userName: '孙七',
    oldLevel: 'BRONZE',
    newLevel: 'SILVER',
    reason: '消费积分达标自动升级',
    changedAt: '2026-03-17 10:20:00',
  },
  {
    id: 'CL003',
    userId: 'U006',
    userName: '周八',
    oldLevel: 'GOLD',
    newLevel: 'SILVER',
    reason: '年度积分清零降级',
    changedAt: '2026-01-01 00:00:00',
  },
];

export const MemberLevel: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [levelRules, setLevelRules] = useState<MemberLevelRule[]>(MOCK_LEVEL_RULES);
  const [statistics, setStatistics] = useState<MemberStatistics>(MOCK_STATISTICS);
  const [changeLogs, setChangeLogs] = useState<LevelChangeLog[]>(MOCK_CHANGE_LOGS);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [selectedRule, setSelectedRule] = useState<MemberLevelRule | null>(null);
  const [benefitInput, setBenefitInput] = useState('');

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

  const loadLevelRules = async () => {
    setLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 500));
      setLevelRules(MOCK_LEVEL_RULES);
      setStatistics(MOCK_STATISTICS);
      setChangeLogs(MOCK_CHANGE_LOGS);
    } catch (error) {
      message.error('加载会员等级数据失败');
    } finally {
      setLoading(false);
    }
  };

  const handleEditRule = (rule: MemberLevelRule) => {
    setSelectedRule(rule);
    form.setFieldsValue({
      minScore: rule.minScore,
      maxScore: rule.maxScore,
      discount: rule.discount * 100,
      pointsMultiplier: rule.pointsMultiplier,
      benefits: rule.benefits,
      isActive: rule.isActive,
    });
    setEditModalVisible(true);
  };

  const handleSaveRule = async (values: any) => {
    try {
      message.success('等级规则更新成功');
      setEditModalVisible(false);
      form.resetFields();
      loadLevelRules();
    } catch (error) {
      message.error('更新失败');
    }
  };

  const handleToggleActive = (rule: MemberLevelRule) => {
    message.success(`${rule.levelName} 已${rule.isActive ? '停用' : '启用'}`);
    loadLevelRules();
  };

  const columns: ColumnsType<MemberLevelRule> = [
    {
      title: '等级',
      dataIndex: 'level',
      key: 'level',
      width: 150,
      render: (level: MemberLevel, record) => (
        <Space>
          <Avatar 
            style={{ backgroundColor: LEVEL_COLORS[level] }} 
            icon={LEVEL_ICONS[level]} 
          />
          <Tag color={LEVEL_COLORS[level]}>{record.levelName}</Tag>
        </Space>
      ),
    },
    {
      title: '积分区间',
      key: 'scoreRange',
      width: 180,
      render: (_, record) => (
        <span>
          {record.minScore.toLocaleString()} - {record.maxScore === 999999999 ? '∞' : record.maxScore.toLocaleString()}
        </span>
      ),
    },
    {
      title: '折扣率',
      dataIndex: 'discount',
      key: 'discount',
      width: 100,
      render: (discount: number) => (
        <Tag color={discount < 1 ? 'green' : 'default'}>
          <PercentageOutlined /> {(discount * 100).toFixed(0)}%
        </Tag>
      ),
    },
    {
      title: '积分倍率',
      dataIndex: 'pointsMultiplier',
      key: 'pointsMultiplier',
      width: 100,
      render: (multiplier: number) => (
        <Tag color="blue">
          <ThunderboltOutlined /> {multiplier}x
        </Tag>
      ),
    },
    {
      title: '权益数量',
      dataIndex: 'benefits',
      key: 'benefits',
      width: 100,
      render: (benefits: string[]) => (
        <Badge count={benefits.length} showZero style={{ backgroundColor: '#1890ff' }} />
      ),
    },
    {
      title: '权益列表',
      dataIndex: 'benefits',
      key: 'benefitsList',
      ellipsis: true,
      render: (benefits: string[]) => (
        <Tooltip title={benefits.join('、')}>
          <span style={{ color: '#666' }}>{benefits.slice(0, 3).join('、')}{benefits.length > 3 ? '...' : ''}</span>
        </Tooltip>
      ),
    },
    {
      title: '状态',
      dataIndex: 'isActive',
      key: 'isActive',
      width: 100,
      render: (isActive: boolean) => (
        <Tag color={isActive ? 'green' : 'red'} icon={isActive ? <CheckCircleOutlined /> : <CloseCircleOutlined />}>
          {isActive ? '启用' : '停用'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      fixed: 'right',
      render: (_, record) => (
        <Space>
          <Button 
            type="link" 
            size="small" 
            icon={<EditOutlined />}
            onClick={() => handleEditRule(record)}
          >
            编辑
          </Button>
          <Button 
            type="link" 
            size="small"
            onClick={() => handleToggleActive(record)}
          >
            {record.isActive ? '停用' : '启用'}
          </Button>
        </Space>
      ),
    },
  ];

  const renderStatistics = () => (
    <Row gutter={16}>
      <Col span={4}>
        <Card>
          <Statistic
            title="会员总数"
            value={statistics.totalMembers}
            prefix={<UserOutlined />}
            valueStyle={{ color: '#1890ff' }}
          />
        </Card>
      </Col>
      <Col span={4}>
        <Card>
          <Statistic
            title="本月升级"
            value={statistics.upgradeCount}
            prefix={<RiseOutlined />}
            valueStyle={{ color: '#52c41a' }}
          />
        </Card>
      </Col>
      <Col span={4}>
        <Card>
          <Statistic
            title="本月降级"
            value={statistics.downgradeCount}
            prefix={<RiseOutlined rotate={180} />}
            valueStyle={{ color: '#ff4d4f' }}
          />
        </Card>
      </Col>
      <Col span={4}>
        <Card>
          <Statistic
            title="平均积分"
            value={statistics.avgMemberScore}
            prefix={<StarOutlined />}
            valueStyle={{ color: '#faad14' }}
          />
        </Card>
      </Col>
      <Col span={8}>
        <Card title="等级分布">
          <Row gutter={8}>
            {Object.entries(statistics.levelDistribution).map(([level, count]) => (
              <Col span={4} key={level}>
                <Tooltip title={`${LEVEL_NAMES[level as MemberLevel]}: ${count}人`}>
                  <div style={{ textAlign: 'center', cursor: 'pointer' }}>
                    <Avatar 
                      size="small" 
                      style={{ backgroundColor: LEVEL_COLORS[level as MemberLevel] }} 
                      icon={LEVEL_ICONS[level as MemberLevel]} 
                    />
                    <div style={{ fontSize: 12, marginTop: 4 }}>{count}</div>
                  </div>
                </Tooltip>
              </Col>
            ))}
          </Row>
        </Card>
      </Col>
    </Row>
  );

  const renderLevelPreview = () => (
    <Card title="等级权益预览" style={{ marginTop: 16 }}>
      <Row gutter={16}>
        {levelRules.filter(r => r.isActive).map(rule => (
          <Col span={4} key={rule.id}>
            <Card 
              size="small"
              style={{ 
                borderColor: LEVEL_COLORS[rule.level],
                borderWidth: 2,
              }}
            >
              <div style={{ textAlign: 'center' }}>
                <Avatar 
                  size={48} 
                  style={{ backgroundColor: LEVEL_COLORS[rule.level] }} 
                  icon={LEVEL_ICONS[rule.level]} 
                />
                <div style={{ fontWeight: 500, marginTop: 8 }}>{rule.levelName}</div>
                <div style={{ fontSize: 12, color: '#999' }}>
                  {rule.minScore.toLocaleString()}+ 积分
                </div>
                <Divider style={{ margin: '12px 0' }} />
                <div style={{ fontSize: 12 }}>
                  <div><PercentageOutlined /> 折扣: {(rule.discount * 100).toFixed(0)}%</div>
                  <div><ThunderboltOutlined /> 积分: {rule.pointsMultiplier}x</div>
                  <div><GiftOutlined /> 权益: {rule.benefits.length}项</div>
                </div>
              </div>
            </Card>
          </Col>
        ))}
      </Row>
    </Card>
  );

  const renderChangeLogs = () => (
    <Card title="等级变动记录" style={{ marginTop: 16 }}>
      <Table
        dataSource={changeLogs}
        rowKey="id"
        size="small"
        pagination={{ pageSize: 5 }}
        columns={[
          {
            title: '用户',
            key: 'user',
            render: (_, record) => (
              <Space>
                <Avatar icon={<UserOutlined />} />
                <span>{record.userName}</span>
              </Space>
            ),
          },
          {
            title: '变动',
            key: 'change',
            render: (_, record) => (
              <Space>
                <Tag color={LEVEL_COLORS[record.oldLevel]}>{LEVEL_NAMES[record.oldLevel]}</Tag>
                <RiseOutlined rotate={record.oldLevel < record.newLevel ? 0 : 180} />
                <Tag color={LEVEL_COLORS[record.newLevel]}>{LEVEL_NAMES[record.newLevel]}</Tag>
              </Space>
            ),
          },
          {
            title: '原因',
            dataIndex: 'reason',
            key: 'reason',
          },
          {
            title: '时间',
            dataIndex: 'changedAt',
            key: 'changedAt',
            render: (time: string) => dayjs(time).format('YYYY-MM-DD HH:mm'),
          },
        ]}
      />
    </Card>
  );

  const renderEditModal = () => (
    <Modal
      title={`编辑 ${selectedRule?.levelName || ''} 规则`}
      open={editModalVisible}
      onCancel={() => {
        setEditModalVisible(false);
        form.resetFields();
      }}
      onOk={() => form.submit()}
      width={600}
    >
      <Alert
        message="修改等级规则将影响所有该等级会员的权益，请谨慎操作"
        type="warning"
        showIcon
        style={{ marginBottom: 16 }}
      />
      
      <Form
        form={form}
        layout="vertical"
        onFinish={handleSaveRule}
      >
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="minScore"
              label="最低积分"
              rules={[{ required: true, message: '请输入最低积分' }]}
            >
              <InputNumber min={0} style={{ width: '100%' }} />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="maxScore"
              label="最高积分"
              rules={[{ required: true, message: '请输入最高积分' }]}
            >
              <InputNumber min={0} style={{ width: '100%' }} />
            </Form.Item>
          </Col>
        </Row>
        
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="discount"
              label="折扣率 (%)"
              rules={[{ required: true, message: '请输入折扣率' }]}
            >
              <Slider 
                min={50} 
                max={100} 
                marks={{ 50: '50%', 75: '75%', 100: '100%' }}
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="pointsMultiplier"
              label="积分倍率"
              rules={[{ required: true, message: '请输入积分倍率' }]}
            >
              <Select>
                <Option value={1.0}>1.0x (标准)</Option>
                <Option value={1.1}>1.1x</Option>
                <Option value={1.2}>1.2x</Option>
                <Option value={1.3}>1.3x</Option>
                <Option value={1.5}>1.5x</Option>
                <Option value={2.0}>2.0x (双倍)</Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>
        
        <Form.Item
          name="benefits"
          label="会员权益"
        >
          <Select mode="tags" placeholder="输入权益后回车添加">
            <Option value="生日优惠">生日优惠</Option>
            <Option value="积分兑换">积分兑换</Option>
            <Option value="专属客服">专属客服</Option>
            <Option value="优先发货">优先发货</Option>
            <Option value="专属折扣">专属折扣</Option>
            <Option value="免费退换">免费退换</Option>
            <Option value="VIP活动">VIP活动</Option>
            <Option value="专属礼品">专属礼品</Option>
            <Option value="私人定制">私人定制</Option>
            <Option value="年度礼包">年度礼包</Option>
          </Select>
        </Form.Item>
        
        <Form.Item
          name="isActive"
          label="状态"
          valuePropName="checked"
        >
          <Switch checkedChildren="启用" unCheckedChildren="停用" />
        </Form.Item>
      </Form>
    </Modal>
  );

  return (
    <div style={{ padding: 24 }}>
      <Card title="会员等级管理" style={{ marginBottom: 16 }}>
        {renderStatistics()}
      </Card>

      <Card>
        <Row style={{ marginBottom: 16 }}>
          <Space>
            <Button type="primary" icon={<SettingOutlined />}>
              批量调整
            </Button>
            <Button icon={<RiseOutlined />}>
              重新计算等级
            </Button>
          </Space>
        </Row>

        <Table
          columns={columns}
          dataSource={levelRules}
          rowKey="id"
          loading={loading}
          pagination={false}
        />
      </Card>

      {renderLevelPreview()}
      {renderChangeLogs()}
      {renderEditModal()}
    </div>
  );
};

export default MemberLevel;
