import { useEffect, useState } from 'react';
import { Button, Form, Input, Select, Table, Typography } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { useSearchParams } from 'react-router-dom';
import { fmtTime, ADMIN_OPTIONS_PAGE_SIZE } from '../lib/constants';
import { useAdminList } from '../lib/useAdminList';
import { request, type Paginated } from '../lib/api';
import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';


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 [cities, setCities] = useState<{ id: string; name: string }[]>([]);
  const [filters, setFilters] = useState<Record<string, string>>({
    ...(initialStoreId ? { storeId: initialStoreId } : {}),
  });

  useEffect(() => {
    request<Paginated<{ id: string; name: string }>>(`/admin/cities?pageSize=${ADMIN_OPTIONS_PAGE_SIZE}`)
      .then((res) => setCities(res.items))
      .catch(() => {});
  }, []);

  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.cityId) qs.set('cityId', filters.cityId);
      if (filters.redeemNo) qs.set('redeemNo', filters.redeemNo);
      return qs;
    },
    [filters],
  );

  const baseColumns: 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 },
  ];

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

  return (
    <div>
      {settingsModal}
      <AdminListHeader title="门店评价" settings={settingsButton} />
      <Form
        form={form}
        layout="inline"
        style={{ marginBottom: 16 }}
        initialValues={filters}
        onFinish={(v) => {
          setFilters({
            storeId: v.storeId || '',
            cityId: v.cityId || '',
            redeemNo: v.redeemNo || '',
          });
          setPage(1);
        }}
      >
        <Form.Item name="cityId" label="城市">
          <Select
            allowClear
            showSearch
            optionFilterProp="label"
            style={{ width: 140 }}
            placeholder="全部"
            options={cities.map((c) => ({ value: c.id, label: c.name }))}
          />
        </Form.Item>
        <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>
  );
}
