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

type Row = {
  id: string; code: string; name: string; province: string; status: string;
  storeCount: number; orderCount: number; createdAt: string;
  partner?: { id: string; companyName: string };
};

type PartnerOption = { id: string; companyName: string };

export default function CitiesPage() {
  const [form] = Form.useForm();
  const [editForm] = Form.useForm();
  const [createForm] = Form.useForm();
  const [filters, setFilters] = useState<Record<string, string>>({});
  const { data, loading, page, pageSize, setPage, setPageSize, reload } = useAdminList<Row>(
    '/admin/cities',
    () => {
      const qs = new URLSearchParams();
      if (filters.name) qs.set('name', filters.name);
      if (filters.code) qs.set('code', filters.code);
      if (filters.status) qs.set('status', filters.status);
      return qs;
    },
    [filters],
  );
  const [detail, setDetail] = useState<Record<string, unknown> | null>(null);
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [createOpen, setCreateOpen] = useState(false);
  const [partners, setPartners] = useState<PartnerOption[]>([]);

  async function loadPartners() {
    const res = await request<Paginated<PartnerOption>>('/admin/partners?pageSize=200');
    setPartners(res.items);
  }

  const columns: ColumnsType<Row> = [
    { title: '编码', dataIndex: 'code', width: 90 },
    { title: '城市', dataIndex: 'name', width: 100 },
    { title: '省份', dataIndex: 'province', width: 90 },
    { title: '状态', dataIndex: 'status', width: 90, render: (s) => <Tag>{CITY_STATUS_LABELS[s] || s}</Tag> },
    { title: '开城合伙人', dataIndex: ['partner', 'companyName'], width: 140, ellipsis: true },
    { title: '门店', dataIndex: 'storeCount', width: 70 },
    { title: '订单', dataIndex: 'orderCount', width: 70 },
    { title: '创建', dataIndex: 'createdAt', width: 160, render: fmtTime },
    {
      title: '操作', width: 80,
      render: (_, row) => (
        <Button type="link" size="small" onClick={async () => {
          const d = await request<Record<string, unknown>>(`/admin/cities/${row.id}`);
          setDetail(d);
          editForm.setFieldsValue({
            ...d,
            partnerId: (d.partner as { id?: string } | null)?.id ?? (d as { partnerId?: string }).partnerId,
          });
          void loadPartners();
          setDrawerOpen(true);
        }}>编辑</Button>
      ),
    },
  ];

  return (
    <div>
      <Space style={{ marginBottom: 16, width: '100%', justifyContent: 'space-between' }}>
        <Typography.Title level={4} style={{ margin: 0 }}>开城城市</Typography.Title>
        <Button type="primary" onClick={() => { void loadPartners(); setCreateOpen(true); }}>新建城市</Button>
      </Space>
      <Form form={form} layout="inline" style={{ marginBottom: 16 }} onFinish={(v) => { setFilters(v); setPage(1); }}>
        <Form.Item name="name" label="城市"><Input allowClear /></Form.Item>
        <Form.Item name="code" label="编码"><Input allowClear /></Form.Item>
        <Form.Item name="status" label="状态">
          <Select allowClear style={{ width: 110 }} options={Object.entries(CITY_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: 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)}
        extra={detail && (
          <Button type="primary" onClick={async () => {
            const v = await editForm.validateFields();
            await request(`/admin/cities/${detail.id}`, { method: 'PUT', body: JSON.stringify(v) });
            message.success('已保存');
            setDrawerOpen(false);
            void reload();
          }}>保存</Button>
        )}>
        {detail && (
          <>
            <Descriptions column={1} bordered size="small" style={{ marginBottom: 16 }}>
              <Descriptions.Item label="编码">{String(detail.code)}</Descriptions.Item>
              <Descriptions.Item label="门店数">{String(detail.storeCount ?? (detail as { _count?: { stores?: number } })._count?.stores ?? '—')}</Descriptions.Item>
            </Descriptions>
            <Form form={editForm} layout="vertical">
              <Form.Item name="name" label="城市名" rules={[{ required: true }]}><Input /></Form.Item>
              <Form.Item name="province" label="省份" rules={[{ required: true }]}><Input /></Form.Item>
              <Form.Item name="partnerId" label="开城合伙人">
                <Select allowClear placeholder="选择合伙人" options={partners.map((p) => ({ value: p.id, label: p.companyName }))} />
              </Form.Item>
              <Form.Item name="status" label="状态">
                <Select options={Object.entries(CITY_STATUS_LABELS).map(([value, label]) => ({ value, label }))} />
              </Form.Item>
              <Form.Item name="localMinQty" label="同城起订量"><InputNumber min={1} style={{ width: '100%' }} /></Form.Item>
              <Form.Item name="crossMinQty" label="跨城起订量"><InputNumber min={1} style={{ width: '100%' }} /></Form.Item>
            </Form>
          </>
        )}
      </Drawer>
      <Modal title="新建开城城市" open={createOpen} onCancel={() => setCreateOpen(false)} onOk={async () => {
        const v = await createForm.validateFields();
        await request('/admin/cities', { method: 'POST', body: JSON.stringify(v) });
        message.success('已创建');
        setCreateOpen(false);
        createForm.resetFields();
        void reload();
      }}>
        <Form form={createForm} layout="vertical">
          <Form.Item name="code" label="城市编码" rules={[{ required: true }]}><Input placeholder="如 ZZ" /></Form.Item>
          <Form.Item name="name" label="城市名" rules={[{ required: true }]}><Input /></Form.Item>
          <Form.Item name="province" label="省份" rules={[{ required: true }]}><Input /></Form.Item>
          <Form.Item name="partnerId" label="开城合伙人">
            <Select allowClear placeholder="选择合伙人" options={partners.map((p) => ({ value: p.id, label: p.companyName }))} />
          </Form.Item>
          <Form.Item name="status" label="状态" initialValue="PENDING">
            <Select options={Object.entries(CITY_STATUS_LABELS).map(([value, label]) => ({ value, label }))} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
