import React, { useEffect, useState } from 'react';
import { Table, Button, Space, Tag, Modal, message, Select } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { getCouponList, deleteCoupon, updateCoupon } from '@/api/coupon';
import type { ColumnsType } from 'antd/es/table';

const { Option } = Select;

const statusMap: Record<string, { color: string; label: string }> = {
  active: { color: 'green', label: '进行中' },
  paused: { color: 'orange', label: '已暂停' },
  ended: { color: 'default', label: '已结束' },
};

const typeMap: Record<string, string> = {
  fixed: '满减券',
  percent: '折扣券',
};

const scopeMap: Record<string, string> = {
  platform: '平台通用',
  merchant: '指定商家',
  room: '指定房源',
};

const CouponList: React.FC = () => {
  const navigate = useNavigate();
  const [data, setData] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(false);
  const [statusFilter, setStatusFilter] = useState<string>('');

  const fetchData = async () => {
    setLoading(true);
    try {
      const res: any = await getCouponList({
        page,
        pageSize: 10,
        status: statusFilter || undefined,
      });
      setData(res.data?.list || []);
      setTotal(res.data?.total || 0);
    } catch (error) {
      message.error('加载失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, [page, statusFilter]);

  const handleDelete = (id: number) => {
    Modal.confirm({
      title: '确认删除',
      content: '删除后无法恢复，确定要删除这个优惠券吗？',
      onOk: async () => {
        try {
          await deleteCoupon(id);
          message.success('删除成功');
          fetchData();
        } catch (error: any) {
          message.error(error.message || '删除失败');
        }
      },
    });
  };

  const handleStatusChange = async (id: number, status: string) => {
    try {
      await updateCoupon(id, { status });
      message.success('状态更新成功');
      fetchData();
    } catch (error) {
      message.error('状态更新失败');
    }
  };

  const columns: ColumnsType<any> = [
    { title: 'ID', dataIndex: 'id', width: 80 },
    { title: '优惠券名称', dataIndex: 'name', width: 200 },
    {
      title: '类型',
      dataIndex: 'type',
      width: 100,
      render: (type) => typeMap[type] || type,
    },
    {
      title: '优惠内容',
      key: 'value',
      width: 120,
      render: (_, record) =>
        record.type === 'fixed' ? `¥${record.value}` : `${record.value}折`,
    },
    {
      title: '使用条件',
      dataIndex: 'minAmount',
      width: 120,
      render: (amount) => (amount > 0 ? `满¥${amount}可用` : '无门槛'),
    },
    {
      title: '适用范围',
      dataIndex: 'scope',
      width: 120,
      render: (scope) => scopeMap[scope] || scope,
    },
    {
      title: '库存',
      key: 'stock',
      width: 150,
      render: (_, record) => (
        <span>
          剩余 {record.remainCount} / 总量 {record.totalCount}
        </span>
      ),
    },
    {
      title: '有效期',
      key: 'date',
      width: 200,
      render: (_, record) => (
        <span>
          {record.startDate} ~ {record.endDate}
        </span>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      render: (status) => (
        <Tag color={statusMap[status]?.color}>{statusMap[status]?.label}</Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      fixed: 'right',
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            size="small"
            onClick={() => navigate(`/coupons/edit/${record.id}`)}
          >
            编辑
          </Button>
          {record.status === 'active' && (
            <Button
              type="link"
              size="small"
              onClick={() => handleStatusChange(record.id, 'paused')}
            >
              暂停
            </Button>
          )}
          {record.status === 'paused' && (
            <Button
              type="link"
              size="small"
              onClick={() => handleStatusChange(record.id, 'active')}
            >
              启用
            </Button>
          )}
          <Button
            type="link"
            size="small"
            danger
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
        <h2>优惠券管理</h2>
        <Space>
          <Select
            placeholder="状态筛选"
            style={{ width: 120 }}
            allowClear
            value={statusFilter || undefined}
            onChange={(value) => {
              setStatusFilter(value || '');
              setPage(1);
            }}
          >
            <Option value="active">进行中</Option>
            <Option value="paused">已暂停</Option>
            <Option value="ended">已结束</Option>
          </Select>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => navigate('/coupons/create')}
          >
            创建优惠券
          </Button>
        </Space>
      </div>
      <Table
        rowKey="id"
        columns={columns}
        dataSource={data}
        loading={loading}
        scroll={{ x: 1500 }}
        pagination={{
          current: page,
          total,
          pageSize: 10,
          onChange: setPage,
        }}
      />
    </div>
  );
};

export default CouponList;
