import { useState } from 'react';
import {
  Button, Descriptions, Drawer, Form, Input, Modal, Space, Table, Typography, message,
} 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; companyName: string; contactPhone: string; address: string;
  storeCount: number; accountCount: number; cityCount: number; createdAt: string;
};

export default function PartnersPage() {
  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/partners',
    () => {
      const qs = new URLSearchParams();
      if (filters.companyName) qs.set('companyName', filters.companyName);
      if (filters.contactPhone) qs.set('contactPhone', filters.contactPhone);
      return qs;
    },
    [filters],
  );
  const [detail, setDetail] = useState<Record<string, unknown> | null>(null);
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [createOpen, setCreateOpen] = useState(false);

  const columns: ColumnsType<Row> = [
    { title: '公司名', dataIndex: 'companyName' },
    { title: '联系电话', dataIndex: 'contactPhone', width: 130 },
    { title: '门店', dataIndex: 'storeCount', width: 70 },
    { title: '账号', dataIndex: 'accountCount', width: 70 },
    { title: '开城城市', dataIndex: 'cityCount', width: 90 },
    { title: '创建', dataIndex: 'createdAt', width: 160, render: fmtTime },
    {
      title: '操作', width: 120,
      render: (_, row) => (
        <Space>
          <Button type="link" size="small" onClick={async () => {
            setDetail(await request(`/admin/partners/${row.id}`));
            setDrawerOpen(true);
          }}>详情</Button>
          <Button type="link" size="small" onClick={() => {
            editForm.setFieldsValue(row);
            setDetail(row as unknown as Record<string, unknown>);
            setDrawerOpen(true);
          }}>编辑</Button>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Space style={{ marginBottom: 16, width: '100%', justifyContent: 'space-between' }}>
        <Typography.Title level={4} style={{ margin: 0 }}>开城合伙人</Typography.Title>
        <Button type="primary" onClick={() => setCreateOpen(true)}>新建开城合伙人</Button>
      </Space>
      <Form form={form} layout="inline" style={{ marginBottom: 16 }} onFinish={(v) => { setFilters(v); setPage(1); }}>
        <Form.Item name="companyName" label="公司"><Input allowClear /></Form.Item>
        <Form.Item name="contactPhone" label="电话"><Input allowClear /></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 ?? []}
        pagination={{ current: page, pageSize, total: data?.total ?? 0, showSizeChanger: true, onChange: (p, ps) => { setPage(p); setPageSize(ps); } }} />
      <Drawer title="开城合伙人详情" width={560} open={drawerOpen} onClose={() => setDrawerOpen(false)}
        extra={detail && (
          <Button type="primary" onClick={async () => {
            const v = await editForm.validateFields();
            await request(`/admin/partners/${detail.id}`, { method: 'PUT', body: JSON.stringify(v) });
            message.success('已保存');
            void reload();
          }}>保存</Button>
        )}>
        {detail && (
          <>
            {Array.isArray(detail.cities) && (
              <Descriptions column={1} bordered size="small" style={{ marginBottom: 16 }} title="关联开城城市">
                {(detail.cities as Array<{ name: string; code: string; status: string }>).map((c) => (
                  <Descriptions.Item key={c.code} label={c.code}>{c.name} ({c.status})</Descriptions.Item>
                ))}
              </Descriptions>
            )}
            <Form form={editForm} layout="vertical" initialValues={detail as Record<string, unknown>}>
              <Form.Item name="companyName" label="公司名" rules={[{ required: true }]}><Input /></Form.Item>
              <Form.Item name="contactPhone" label="联系电话" rules={[{ required: true }]}><Input /></Form.Item>
              <Form.Item name="address" label="地址" rules={[{ required: true }]}><Input /></Form.Item>
              <Form.Item name="bankAccountName" label="户名"><Input /></Form.Item>
              <Form.Item name="bankAccountNo" label="账号"><Input /></Form.Item>
            </Form>
          </>
        )}
      </Drawer>
      <Modal title="新建开城合伙人" open={createOpen} onCancel={() => setCreateOpen(false)} onOk={async () => {
        const v = await createForm.validateFields();
        await request('/admin/partners', { method: 'POST', body: JSON.stringify(v) });
        message.success('已创建');
        setCreateOpen(false);
        createForm.resetFields();
        void reload();
      }}>
        <Form form={createForm} layout="vertical">
          <Form.Item name="companyName" label="公司名" rules={[{ required: true }]}><Input /></Form.Item>
          <Form.Item name="contactPhone" label="联系电话" rules={[{ required: true }]}><Input /></Form.Item>
          <Form.Item name="address" label="地址" rules={[{ required: true }]}><Input /></Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
