import { useState } from 'react';
import { Button, Descriptions, Drawer, Form, Input, Popconfirm, Select, Table, Tag, Typography, message } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { request } from '../lib/api';
import { COUPON_STATUS_LABELS, fmtTime } from '../lib/constants';
import { useAdminList } from '../lib/useAdminList';

type Row = {
  id: string; couponNo: string; totalAmount: number; balance: number; usedAmount: number;
  status: string; sourceProduct: string; createdAt: string;
  user?: { userNo: string; phone: string | null };
  order?: { orderNo: string };
};

export default function BenefitCouponsPage() {
  const [form] = Form.useForm();
  const [filters, setFilters] = useState<Record<string, string>>({});
  const { data, loading, page, pageSize, setPage, setPageSize, reload } = useAdminList<Row>(
    '/admin/benefit/coupons',
    () => {
      const qs = new URLSearchParams();
      if (filters.couponNo) qs.set('couponNo', filters.couponNo);
      if (filters.status) qs.set('status', filters.status);
      if (filters.userId) qs.set('userId', filters.userId);
      return qs;
    },
    [filters],
  );
  const [detail, setDetail] = useState<Record<string, unknown> | null>(null);
  const [drawerOpen, setDrawerOpen] = useState(false);

  const columns: ColumnsType<Row> = [
    { title: '券号', dataIndex: 'couponNo', width: 200, ellipsis: false },
    { title: '用户', dataIndex: ['user', 'userNo'], width: 120, ellipsis: false },
    { title: '订单', dataIndex: ['order', 'orderNo'], width: 180, ellipsis: false },
    { title: '总额', dataIndex: 'totalAmount', width: 80, render: (v) => `¥${v}` },
    { title: '余额', dataIndex: 'balance', width: 80, render: (v) => `¥${v}` },
    { title: '状态', dataIndex: 'status', width: 90, render: (s) => <Tag>{COUPON_STATUS_LABELS[s] || s}</Tag> },
    { title: '来源', dataIndex: 'sourceProduct', ellipsis: true },
    { title: '创建', dataIndex: 'createdAt', width: 160, render: fmtTime },
    {
      title: '操作', width: 80,
      render: (_, row) => (
        <Button type="link" size="small" onClick={async () => {
          setDetail(await request(`/admin/benefit/coupons/${row.id}`));
          setDrawerOpen(true);
        }}>详情</Button>
      ),
    },
  ];

  return (
    <div>
      <Typography.Title level={4}>好客权益券</Typography.Title>
      <Form form={form} layout="inline" style={{ marginBottom: 16 }} onFinish={(v) => { setFilters(v); setPage(1); }}>
        <Form.Item name="couponNo" label="券号"><Input allowClear /></Form.Item>
        <Form.Item name="status" label="状态">
          <Select allowClear style={{ width: 100 }} options={Object.entries(COUPON_STATUS_LABELS).map(([value, label]) => ({ value, label }))} />
        </Form.Item>
        <Form.Item><Button type="primary" htmlType="submit">查询</Button></Form.Item>
      </Form>
      <Table rowKey="id" className="admin-table-nowrap" loading={loading} columns={columns} dataSource={data?.items ?? []} scroll={{ x: 1100 }}
        pagination={{ current: page, pageSize, total: data?.total ?? 0, showSizeChanger: true, onChange: (p, ps) => { setPage(p); setPageSize(ps); } }} />
      <Drawer title="权益券详情" width={560} open={drawerOpen} onClose={() => setDrawerOpen(false)}
        extra={detail && detail.status !== 'VOID' && (
          <Popconfirm title="确认作废此券？" onConfirm={async () => {
            await request(`/admin/benefit/coupons/${detail.id}/void`, { method: 'POST' });
            message.success('已作废');
            setDrawerOpen(false);
            void reload();
          }}>
            <Button danger>作废</Button>
          </Popconfirm>
        )}>
        {detail && (
          <Descriptions column={1} bordered size="small">
            <Descriptions.Item label="券号">{String(detail.couponNo)}</Descriptions.Item>
            <Descriptions.Item label="总额">¥{String(detail.totalAmount)}</Descriptions.Item>
            <Descriptions.Item label="余额">¥{String(detail.balance)}</Descriptions.Item>
            <Descriptions.Item label="状态">{COUPON_STATUS_LABELS[String(detail.status)] || String(detail.status)}</Descriptions.Item>
            <Descriptions.Item label="来源">{String(detail.sourceProduct)}</Descriptions.Item>
          </Descriptions>
        )}
      </Drawer>
    </div>
  );
}
