import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  InputNumber,
  Select,
  Tag,
  Tooltip,
  Row,
  Col,
  Statistic,
  message,
  Badge,
  DatePicker,
  Tabs,
  Timeline,
  Descriptions,
  Divider,
  Alert,
  Result,
} from 'antd';
import {
  PlusOutlined,
  MinusOutlined,
  LockOutlined,
  UnlockOutlined,
  HistoryOutlined,
  StarOutlined,
  UserOutlined,
  ClockCircleOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  ExclamationCircleOutlined,
  GiftOutlined,
  ShoppingCartOutlined,
  TrophyOutlined,
  EditOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import { userAssetDataSource, PointsRecord, UserAsset } from '@/services/userAssetDataSource';

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

type PointsSourceType = 
  | 'PURCHASE'
  | 'REVIEW'
  | 'REFERRAL'
  | 'PROMOTION'
  | 'ADMIN_ADJUST'
  | 'EXPIRED'
  | 'REFUND'
  | 'MANUAL_DEDUCT';

type PointsStatus = 'PENDING' | 'CONFIRMED' | 'FROZEN' | 'EXPIRED' | 'CANCELLED';

interface PointsRecord {
  id: string;
  tenantId: string;
  shopId: string;
  userId: string;
  userName: string;
  taskId?: string;
  traceId: string;
  businessType: 'TOC' | 'TOB';
  points: number;
  balance: number;
  sourceType: PointsSourceType;
  sourceId?: string;
  description: string;
  status: PointsStatus;
  expiredAt?: string;
  createdAt: string;
}

interface PointsOperationInput {
  tenantId: string;
  shopId: string;
  userId: string;
  points: number;
  sourceType: PointsSourceType;
  description: string;
  taskId?: string;
  traceId: string;
  businessType: 'TOC' | 'TOB';
  expiredAt?: string;
}

interface PointsStatistics {
  totalEarned: number;
  totalSpent: number;
  totalFrozen: number;
  totalExpired: number;
  todayEarned: number;
  todaySpent: number;
}

const SOURCE_TYPE_NAMES: Record<PointsSourceType, string> = {
  PURCHASE: '购物获得',
  REVIEW: '评价奖励',
  REFERRAL: '推荐奖励',
  PROMOTION: '活动奖励',
  ADMIN_ADJUST: '管理员调整',
  EXPIRED: '积分过期',
  REFUND: '退款返还',
  MANUAL_DEDUCT: '手动扣减',
};

const SOURCE_TYPE_COLORS: Record<PointsSourceType, string> = {
  PURCHASE: 'green',
  REVIEW: 'blue',
  REFERRAL: 'purple',
  PROMOTION: 'orange',
  ADMIN_ADJUST: 'cyan',
  EXPIRED: 'red',
  REFUND: 'gold',
  MANUAL_DEDUCT: 'magenta',
};

const STATUS_NAMES: Record<PointsStatus, string> = {
  PENDING: '待确认',
  CONFIRMED: '已确认',
  FROZEN: '已冻结',
  EXPIRED: '已过期',
  CANCELLED: '已取消',
};

const STATUS_COLORS: Record<PointsStatus, string> = {
  PENDING: 'gold',
  CONFIRMED: 'green',
  FROZEN: 'blue',
  EXPIRED: 'red',
  CANCELLED: 'default',
};

const STATUS_ICONS: Record<PointsStatus, React.ReactNode> = {
  PENDING: <ClockCircleOutlined />,
  CONFIRMED: <CheckCircleOutlined />,
  FROZEN: <LockOutlined />,
  EXPIRED: <ExclamationCircleOutlined />,
  CANCELLED: <CloseCircleOutlined />,
};

const MOCK_POINTS_RECORDS: PointsRecord[] = [
  {
    id: 'PR001',
    tenantId: 'T001',
    shopId: 'S001',
    userId: 'U001',
    userName: '张三',
    traceId: 'TR001',
    businessType: 'TOC',
    points: 580,
    balance: 5680,
    sourceType: 'PURCHASE',
    description: '订单 ORD-20260318-001 购物奖励',
    status: 'CONFIRMED',
    createdAt: '2026-03-18 14:30:00',
  },
  {
    id: 'PR002',
    tenantId: 'T001',
    shopId: 'S001',
    userId: 'U001',
    userName: '张三',
    traceId: 'TR002',
    businessType: 'TOC',
    points: 50,
    balance: 5100,
    sourceType: 'REVIEW',
    description: '商品评价奖励',
    status: 'CONFIRMED',
    createdAt: '2026-03-17 10:20:00',
  },
  {
    id: 'PR003',
    tenantId: 'T001',
    shopId: 'S001',
    userId: 'U002',
    userName: '李四',
    traceId: 'TR003',
    businessType: 'TOC',
    points: 200,
    balance: 2300,
    sourceType: 'REFERRAL',
    description: '推荐新用户注册奖励',
    status: 'CONFIRMED',
    createdAt: '2026-03-16 16:45:00',
  },
  {
    id: 'PR004',
    tenantId: 'T001',
    shopId: 'S001',
    userId: 'U003',
    userName: '王五',
    traceId: 'TR004',
    businessType: 'TOC',
    points: -500,
    balance: 15800,
    sourceType: 'MANUAL_DEDUCT',
    description: '积分兑换优惠券',
    status: 'CONFIRMED',
    createdAt: '2026-03-15 09:10:00',
  },
  {
    id: 'PR005',
    tenantId: 'T001',
    shopId: 'S001',
    userId: 'U001',
    userName: '张三',
    traceId: 'TR005',
    businessType: 'TOC',
    points: 100,
    balance: 5050,
    sourceType: 'PROMOTION',
    description: '新春活动奖励',
    status: 'FROZEN',
    expiredAt: '2026-04-15 23:59:59',
    createdAt: '2026-03-10 00:00:00',
  },
  {
    id: 'PR006',
    tenantId: 'T001',
    shopId: 'S001',
    userId: 'U004',
    userName: '赵六',
    traceId: 'TR006',
    businessType: 'TOC',
    points: -200,
    balance: 850,
    sourceType: 'EXPIRED',
    description: '2025年积分过期清理',
    status: 'EXPIRED',
    createdAt: '2026-01-01 00:00:00',
  },
];

const MOCK_STATISTICS: PointsStatistics = {
  totalEarned: 156800,
  totalSpent: 45200,
  totalFrozen: 8500,
  totalExpired: 3200,
  todayEarned: 1580,
  todaySpent: 450,
};

export const PointsManage: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [pointsRecords, setPointsRecords] = useState<PointsRecord[]>(MOCK_POINTS_RECORDS);
  const [statistics, setStatistics] = useState<PointsStatistics>(MOCK_STATISTICS);
  const [operationModalVisible, setOperationModalVisible] = useState(false);
  const [operationType, setOperationType] = useState<'ADD' | 'DEDUCT' | 'FREEZE'>('ADD');
  const [selectedRecord, setSelectedRecord] = useState<PointsRecord | null>(null);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [searchParams, setSearchParams] = useState({
    userId: '',
    sourceType: undefined as PointsSourceType | undefined,
    status: undefined as PointsStatus | undefined,
    dateRange: null as [dayjs.Dayjs, dayjs.Dayjs] | null,
  });

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

  const loadPointsRecords = async () => {
    setLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 500));
      setPointsRecords(MOCK_POINTS_RECORDS);
      setStatistics(MOCK_STATISTICS);
    } catch (error) {
      message.error('加载积分记录失败');
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = () => {
    let filtered = [...MOCK_POINTS_RECORDS];
    
    if (searchParams.userId) {
      filtered = filtered.filter(
        r => r.userId.includes(searchParams.userId) || 
             r.userName.includes(searchParams.userId)
      );
    }
    
    if (searchParams.sourceType) {
      filtered = filtered.filter(r => r.sourceType === searchParams.sourceType);
    }
    
    if (searchParams.status) {
      filtered = filtered.filter(r => r.status === searchParams.status);
    }
    
    if (searchParams.dateRange) {
      const [start, end] = searchParams.dateRange;
      filtered = filtered.filter(r => {
        const date = dayjs(r.createdAt);
        return date.isAfter(start) && date.isBefore(end);
      });
    }
    
    setPointsRecords(filtered);
  };

  const handleReset = () => {
    setSearchParams({
      userId: '',
      sourceType: undefined,
      status: undefined,
      dateRange: null,
    });
    setPointsRecords(MOCK_POINTS_RECORDS);
  };

  const handleOperation = async (values: any) => {
    try {
      const traceId = `TR${Date.now()}`;
      
      message.success(`${operationType === 'ADD' ? '增加' : operationType === 'DEDUCT' ? '扣减' : '冻结'}积分成功`);
      setOperationModalVisible(false);
      form.resetFields();
      loadPointsRecords();
    } catch (error) {
      message.error('操作失败');
    }
  };

  const showRecordDetail = (record: PointsRecord) => {
    setSelectedRecord(record);
    setDetailModalVisible(true);
  };

  const columns: ColumnsType<PointsRecord> = [
    {
      title: '用户',
      key: 'user',
      width: 140,
      render: (_, record) => (
        <Space>
          <UserOutlined />
          <div>
            <div style={{ fontWeight: 500 }}>{record.userName}</div>
            <div style={{ fontSize: 12, color: '#999' }}>{record.userId}</div>
          </div>
        </Space>
      ),
    },
    {
      title: '积分变动',
      dataIndex: 'points',
      key: 'points',
      width: 120,
      align: 'right',
      render: (points: number) => (
        <span style={{ 
          color: points > 0 ? '#52c41a' : '#ff4d4f',
          fontWeight: 500,
          fontSize: 14,
        }}>
          {points > 0 ? '+' : ''}{points.toLocaleString()}
        </span>
      ),
      sorter: (a, b) => a.points - b.points,
    },
    {
      title: '变动后余额',
      dataIndex: 'balance',
      key: 'balance',
      width: 120,
      align: 'right',
      render: (balance: number) => (
        <span style={{ color: '#1890ff' }}>{balance.toLocaleString()}</span>
      ),
    },
    {
      title: '来源类型',
      dataIndex: 'sourceType',
      key: 'sourceType',
      width: 120,
      render: (type: PointsSourceType) => (
        <Tag color={SOURCE_TYPE_COLORS[type]}>
          {SOURCE_TYPE_NAMES[type]}
        </Tag>
      ),
      filters: Object.entries(SOURCE_TYPE_NAMES).map(([key, name]) => ({
        text: name,
        value: key,
      })),
      onFilter: (value, record) => record.sourceType === value,
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      width: 250,
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: PointsStatus) => (
        <Tag color={STATUS_COLORS[status]} icon={STATUS_ICONS[status]}>
          {STATUS_NAMES[status]}
        </Tag>
      ),
      filters: Object.entries(STATUS_NAMES).map(([key, name]) => ({
        text: name,
        value: key,
      })),
      onFilter: (value, record) => record.status === value,
    },
    {
      title: '业务类型',
      dataIndex: 'businessType',
      key: 'businessType',
      width: 90,
      render: (type: 'TOC' | 'TOB') => (
        <Tag color={type === 'TOC' ? 'blue' : 'green'}>{type}</Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      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.createdAt).getTime() - new Date(b.createdAt).getTime(),
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      fixed: 'right',
      render: (_, record) => (
        <Button type="link" size="small" onClick={() => showRecordDetail(record)}>
          详情
        </Button>
      ),
    },
  ];

  const renderStatistics = () => (
    <Row gutter={16}>
      <Col span={4}>
        <Card>
          <Statistic
            title="累计获得"
            value={statistics.totalEarned}
            prefix={<StarOutlined style={{ color: '#52c41a' }} />}
            valueStyle={{ color: '#52c41a' }}
          />
        </Card>
      </Col>
      <Col span={4}>
        <Card>
          <Statistic
            title="累计消耗"
            value={statistics.totalSpent}
            prefix={<MinusOutlined style={{ color: '#ff4d4f' }} />}
            valueStyle={{ color: '#ff4d4f' }}
          />
        </Card>
      </Col>
      <Col span={4}>
        <Card>
          <Statistic
            title="冻结积分"
            value={statistics.totalFrozen}
            prefix={<LockOutlined style={{ color: '#1890ff' }} />}
            valueStyle={{ color: '#1890ff' }}
          />
        </Card>
      </Col>
      <Col span={4}>
        <Card>
          <Statistic
            title="已过期"
            value={statistics.totalExpired}
            prefix={<ExclamationCircleOutlined style={{ color: '#999' }} />}
            valueStyle={{ color: '#999' }}
          />
        </Card>
      </Col>
      <Col span={4}>
        <Card>
          <Statistic
            title="今日获得"
            value={statistics.todayEarned}
            prefix={<TrophyOutlined style={{ color: '#faad14' }} />}
            valueStyle={{ color: '#faad14' }}
          />
        </Card>
      </Col>
      <Col span={4}>
        <Card>
          <Statistic
            title="今日消耗"
            value={statistics.todaySpent}
            prefix={<ShoppingCartOutlined style={{ color: '#722ed1' }} />}
            valueStyle={{ color: '#722ed1' }}
          />
        </Card>
      </Col>
    </Row>
  );

  const renderOperationModal = () => (
    <Modal
      title={
        operationType === 'ADD' ? '增加积分' : 
        operationType === 'DEDUCT' ? '扣减积分' : '冻结积分'
      }
      open={operationModalVisible}
      onCancel={() => {
        setOperationModalVisible(false);
        form.resetFields();
      }}
      onOk={() => form.submit()}
      width={500}
    >
      <Alert
        message={
          operationType === 'ADD' ? '增加积分后立即生效，请确认操作' :
          operationType === 'DEDUCT' ? '扣减积分将从用户可用积分中扣除，请确认' :
          '冻结积分将暂时不可使用，解冻后恢复'
        }
        type="warning"
        showIcon
        style={{ marginBottom: 16 }}
      />
      
      <Form
        form={form}
        layout="vertical"
        onFinish={handleOperation}
      >
        <Form.Item
          name="userId"
          label="用户ID"
          rules={[{ required: true, message: '请输入用户ID' }]}
        >
          <Input placeholder="输入用户ID" />
        </Form.Item>
        
        <Form.Item
          name="points"
          label="积分数量"
          rules={[{ required: true, message: '请输入积分数量' }]}
        >
          <InputNumber 
            min={1} 
            style={{ width: '100%' }} 
            placeholder="输入积分数量"
          />
        </Form.Item>
        
        <Form.Item
          name="sourceType"
          label="来源类型"
          rules={[{ required: true, message: '请选择来源类型' }]}
        >
          <Select placeholder="选择来源类型">
            {operationType === 'ADD' && (
              <>
                <Option value="PURCHASE">购物获得</Option>
                <Option value="REVIEW">评价奖励</Option>
                <Option value="REFERRAL">推荐奖励</Option>
                <Option value="PROMOTION">活动奖励</Option>
                <Option value="ADMIN_ADJUST">管理员调整</Option>
              </>
            )}
            {operationType === 'DEDUCT' && (
              <>
                <Option value="MANUAL_DEDUCT">手动扣减</Option>
                <Option value="EXPIRED">积分过期</Option>
              </>
            )}
            {operationType === 'FREEZE' && (
              <Option value="ADMIN_ADJUST">管理员冻结</Option>
            )}
          </Select>
        </Form.Item>
        
        <Form.Item
          name="description"
          label="操作说明"
          rules={[{ required: true, message: '请输入操作说明' }]}
        >
          <Input.TextArea rows={3} placeholder="输入操作说明" />
        </Form.Item>
        
        {operationType === 'ADD' && (
          <Form.Item
            name="expiredAt"
            label="过期时间"
          >
            <DatePicker style={{ width: '100%' }} placeholder="选择过期时间（可选）" />
          </Form.Item>
        )}
      </Form>
    </Modal>
  );

  const renderDetailModal = () => {
    if (!selectedRecord) return null;

    return (
      <Modal
        title="积分记录详情"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={null}
        width={600}
      >
        <Descriptions bordered column={2}>
          <Descriptions.Item label="记录ID">{selectedRecord.id}</Descriptions.Item>
          <Descriptions.Item label="追踪ID">{selectedRecord.traceId}</Descriptions.Item>
          <Descriptions.Item label="用户ID">{selectedRecord.userId}</Descriptions.Item>
          <Descriptions.Item label="用户名">{selectedRecord.userName}</Descriptions.Item>
          <Descriptions.Item label="积分变动">
            <span style={{ 
              color: selectedRecord.points > 0 ? '#52c41a' : '#ff4d4f',
              fontWeight: 500,
            }}>
              {selectedRecord.points > 0 ? '+' : ''}{selectedRecord.points}
            </span>
          </Descriptions.Item>
          <Descriptions.Item label="变动后余额">{selectedRecord.balance}</Descriptions.Item>
          <Descriptions.Item label="来源类型">
            <Tag color={SOURCE_TYPE_COLORS[selectedRecord.sourceType]}>
              {SOURCE_TYPE_NAMES[selectedRecord.sourceType]}
            </Tag>
          </Descriptions.Item>
          <Descriptions.Item label="状态">
            <Tag color={STATUS_COLORS[selectedRecord.status]} icon={STATUS_ICONS[selectedRecord.status]}>
              {STATUS_NAMES[selectedRecord.status]}
            </Tag>
          </Descriptions.Item>
          <Descriptions.Item label="业务类型">
            <Tag color={selectedRecord.businessType === 'TOC' ? 'blue' : 'green'}>
              {selectedRecord.businessType}
            </Tag>
          </Descriptions.Item>
          <Descriptions.Item label="创建时间">{selectedRecord.createdAt}</Descriptions.Item>
          <Descriptions.Item label="描述" span={2}>{selectedRecord.description}</Descriptions.Item>
          {selectedRecord.expiredAt && (
            <Descriptions.Item label="过期时间">{selectedRecord.expiredAt}</Descriptions.Item>
          )}
          {selectedRecord.sourceId && (
            <Descriptions.Item label="来源ID">{selectedRecord.sourceId}</Descriptions.Item>
          )}
        </Descriptions>
      </Modal>
    );
  };

  return (
    <div style={{ padding: 24 }}>
      <Card title="积分管理" style={{ marginBottom: 16 }}>
        {renderStatistics()}
      </Card>

      <Card>
        <Row gutter={16} style={{ marginBottom: 16 }}>
          <Col span={4}>
            <Input
              placeholder="搜索用户ID/名称"
              value={searchParams.userId}
              onChange={e => setSearchParams({ ...searchParams, userId: e.target.value })}
              onPressEnter={handleSearch}
            />
          </Col>
          <Col span={3}>
            <Select
              placeholder="来源类型"
              value={searchParams.sourceType}
              onChange={value => setSearchParams({ ...searchParams, sourceType: value })}
              allowClear
              style={{ width: '100%' }}
            >
              {Object.entries(SOURCE_TYPE_NAMES).map(([key, name]) => (
                <Option key={key} value={key}>{name}</Option>
              ))}
            </Select>
          </Col>
          <Col span={3}>
            <Select
              placeholder="状态"
              value={searchParams.status}
              onChange={value => setSearchParams({ ...searchParams, status: value })}
              allowClear
              style={{ width: '100%' }}
            >
              {Object.entries(STATUS_NAMES).map(([key, name]) => (
                <Option key={key} value={key}>{name}</Option>
              ))}
            </Select>
          </Col>
          <Col span={6}>
            <RangePicker
              value={searchParams.dateRange}
              onChange={(dates) => setSearchParams({ 
                ...searchParams, 
                dateRange: dates as [dayjs.Dayjs, dayjs.Dayjs] | null 
              })}
              style={{ width: '100%' }}
            />
          </Col>
          <Col span={4}>
            <Space>
              <Button type="primary" onClick={handleSearch}>搜索</Button>
              <Button onClick={handleReset}>重置</Button>
            </Space>
          </Col>
        </Row>

        <Row style={{ marginBottom: 16 }}>
          <Space>
            <Button 
              type="primary" 
              icon={<PlusOutlined />}
              onClick={() => {
                setOperationType('ADD');
                setOperationModalVisible(true);
              }}
            >
              增加积分
            </Button>
            <Button 
              danger
              icon={<MinusOutlined />}
              onClick={() => {
                setOperationType('DEDUCT');
                setOperationModalVisible(true);
              }}
            >
              扣减积分
            </Button>
            <Button 
              icon={<LockOutlined />}
              onClick={() => {
                setOperationType('FREEZE');
                setOperationModalVisible(true);
              }}
            >
              冻结积分
            </Button>
          </Space>
        </Row>

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

      {renderOperationModal()}
      {renderDetailModal()}
    </div>
  );
};

export default PointsManage;
