import { useState } from 'react';
import { Button, Form, Input, Table, Typography } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { useSearchParams } from 'react-router-dom';
import { fmtTime } from '../lib/constants';
import { useAdminList } from '../lib/useAdminList';

type Row = {
  id: string;
  serviceScore: number;
  envScore: number;
  createdAt: string;
  redeemNo: string;
  redeemAmount: number;
  store?: { id: string; name: string; cityName?: string };
  user?: { userNo: string; phone: string | null; nickname: string | null };
};

export default function StoreRatingsPage() {
  const [searchParams] = useSearchParams();
  const initialStoreId = searchParams.get('storeId') || '';
  const [form] = Form.useForm();
  const [filters, setFilters] = useState<Record<string, string>>({
    ...(initialStoreId ? { storeId: initialStoreId } : {}),
  });

  const { data, loading, page, pageSize, setPage, setPageSize } = useAdminList<Row>(
    '/admin/store-ratings',
    () => {
      const qs = new URLSearchParams();
      if (filters.storeId) qs.set('storeId', filters.storeId);
      if (filters.redeemNo) qs.set('redeemNo', filters.redeemNo);
      return qs;
    },
    [filters],
  );

  const columns: ColumnsType<Row> = [
    { title: '核销号', dataIndex: 'redeemNo', width: 180 },
    {
      title: '门店',
      dataIndex: ['store', 'name'],
      render: (v, row) => (row.store?.cityName ? `${v}（${row.store.cityName}）` : v),
    },
    {
      title: '用户',
      width: 140,
      render: (_, row) => row.user?.phone || row.user?.userNo || '-',
    },
    { title: '核销额', dataIndex: 'redeemAmount', width: 90, render: (v) => `¥${v}` },
    { title: '服务分', dataIndex: 'serviceScore', width: 80 },
    { title: '环境分', dataIndex: 'envScore', width: 80 },
    { title: '评价时间', dataIndex: 'createdAt', width: 170, render: fmtTime },
  ];

  return (
    <div>
      <Typography.Title level={4} style={{ marginTop: 0 }}>
        门店评价
      </Typography.Title>
      <Form
        form={form}
        layout="inline"
        style={{ marginBottom: 16 }}
        initialValues={filters}
        onFinish={(v) => {
          setFilters({
            storeId: v.storeId || '',
            redeemNo: v.redeemNo || '',
          });
          setPage(1);
        }}
      >
        <Form.Item name="storeId" label="门店ID">
          <Input allowClear placeholder="storeId" />
        </Form.Item>
        <Form.Item name="redeemNo" label="核销号">
          <Input allowClear />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">
            查询
          </Button>
        </Form.Item>
      </Form>
      <Table
        rowKey="id"
        loading={loading}
        columns={columns}
        dataSource={data?.items ?? []}
        pagination={{
          current: page,
          pageSize,
          total: data?.total ?? 0,
          showSizeChanger: true,
          onChange: (p, ps) => {
            setPage(p);
            setPageSize(ps);
          },
        }}
      />
    </div>
  );
}
