import { useState } from 'react';
import { Form, Input, Select, Button, Table, Tag, Typography } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { LEDGER_TYPE_LABELS, fmtTime } from '../lib/constants';
import { useAdminList } from '../lib/useAdminList';
import { useAdminListColumns } from '../lib/useAdminListColumns';


type Row = {
  id: string; type: string; amount: number; balanceAfter: number; remark: string | null; createdAt: string;
  user?: { userNo: string }; coupon?: { couponNo: string };
};

export default function BenefitLedgersPage() {
  const [form] = Form.useForm();
  const [filters, setFilters] = useState<Record<string, string>>({});
  const { data, loading, page, pageSize, setPage, setPageSize } = useAdminList<Row>(
    '/admin/benefit/ledgers',
    () => {
      const qs = new URLSearchParams();
      if (filters.userId) qs.set('userId', filters.userId);
      if (filters.couponId) qs.set('couponId', filters.couponId);
      if (filters.type) qs.set('type', filters.type);
      return qs;
    },
    [filters],
  );

  const baseColumns: ColumnsType<Row> = [
    { title: '类型', dataIndex: 'type', width: 90, render: (t) => <Tag>{LEDGER_TYPE_LABELS[t] || t}</Tag> },
    { title: '用户', dataIndex: ['user', 'userNo'], width: 120, ellipsis: false },
    { title: '券号', dataIndex: ['coupon', 'couponNo'], width: 200, ellipsis: false },
    { title: '变动', dataIndex: 'amount', width: 90, render: (v) => `${v >= 0 ? '+' : ''}${v}` },
    { title: '余额后', dataIndex: 'balanceAfter', width: 90 },
    { title: '备注', dataIndex: 'remark' },
    { title: '时间', dataIndex: 'createdAt', width: 160, render: fmtTime },
  ];

  const { columns, settingsButton, settingsModal } = useAdminListColumns('benefit-ledgers', baseColumns, { page, pageSize });

  return (
    <div>
      {settingsModal}
      <Typography.Title level={4}>权益流水</Typography.Title>
          {settingsButton}
      <Form form={form} layout="inline" style={{ marginBottom: 16 }} onFinish={(v) => { setFilters(v); setPage(1); }}>
        <Form.Item name="userId" label="用户ID"><Input allowClear /></Form.Item>
        <Form.Item name="couponId" label="券ID"><Input allowClear /></Form.Item>
        <Form.Item name="type" label="类型">
          <Select allowClear style={{ width: 100 }} options={Object.entries(LEDGER_TYPE_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: 'max-content' }}
        pagination={{ current: page, pageSize, total: data?.total ?? 0, showSizeChanger: true, onChange: (p, ps) => { setPage(p); setPageSize(ps); } }} />
    </div>
  );
}
