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

type Row = {
  id: string; redeemNo: string; amount: number; settleAmount: number; createdAt: string;
  user?: { userNo: string; phone: string | null };
  store?: { name: string; cityName: string };
  coupon?: { couponNo: string };
};

export default function RedeemRecordsPage() {
  const [form] = Form.useForm();
  const [filters, setFilters] = useState<Record<string, string>>({});
  const { data, loading, page, pageSize, setPage, setPageSize } = useAdminList<Row>(
    '/admin/redeem-records',
    () => {
      const qs = new URLSearchParams();
      if (filters.redeemNo) qs.set('redeemNo', filters.redeemNo);
      if (filters.storeId) qs.set('storeId', filters.storeId);
      return qs;
    },
    [filters],
  );
  const [detail, setDetail] = useState<Record<string, unknown> | null>(null);
  const [drawerOpen, setDrawerOpen] = useState(false);

  const columns: ColumnsType<Row> = [
    { title: '核销号', dataIndex: 'redeemNo', width: 180 },
    { title: '用户', dataIndex: ['user', 'userNo'], width: 110 },
    { title: '门店', dataIndex: ['store', 'name'] },
    { title: '核销额', dataIndex: 'amount', width: 90, render: (v) => `¥${v}` },
    { title: '结算额', dataIndex: 'settleAmount', width: 90, render: (v) => `¥${v}` },
    { title: '券号', dataIndex: ['coupon', 'couponNo'], width: 160 },
    { title: '时间', dataIndex: 'createdAt', width: 160, render: fmtTime },
    {
      title: '操作', width: 80,
      render: (_, row) => (
        <Button type="link" size="small" onClick={async () => {
          setDetail(await request(`/admin/redeem-records/${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="redeemNo" label="核销号"><Input allowClear /></Form.Item>
        <Form.Item name="storeId" label="门店ID"><Input allowClear /></Form.Item>
      </Form>
      <Table rowKey="id" loading={loading} columns={columns} dataSource={data?.items ?? []} scroll={{ x: 1000 }}
        pagination={{ current: page, pageSize, total: data?.total ?? 0, showSizeChanger: true, onChange: (p, ps) => { setPage(p); setPageSize(ps); } }} />
      <Drawer title="核销详情" width={520} open={drawerOpen} onClose={() => setDrawerOpen(false)}>
        {detail && (
          <Descriptions column={1} bordered size="small">
            <Descriptions.Item label="核销号">{String(detail.redeemNo)}</Descriptions.Item>
            <Descriptions.Item label="核销额">¥{String(detail.amount)}</Descriptions.Item>
            <Descriptions.Item label="结算额">¥{String(detail.settleAmount)}</Descriptions.Item>
            <Descriptions.Item label="时间">{fmtTime(String(detail.createdAt))}</Descriptions.Item>
          </Descriptions>
        )}
      </Drawer>
    </div>
  );
}
