import { PlusOutlined } from '@ant-design/icons';
import { ActionType, ProColumns, ProTable } from '@ant-design/pro-components';
import { Button, Form, Input, Modal, Space, Tag, message } from 'antd';
import { useRef, useState } from 'react';
import { createSupplier, deleteSupplier, listSuppliers, updateSupplier } from '@/services/api';
import type { Supplier } from '@/types/api';

const STATUS_MAP: Record<number, { text: string; color: string }> = {
  0: { text: '停用', color: 'default' },
  1: { text: '正常', color: 'success' },
};

const SuppliersPage: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [form] = Form.useForm();
  const [modalOpen, setModalOpen] = useState(false);
  const [editing, setEditing] = useState<Supplier | null>(null);

  const openCreate = () => {
    setEditing(null);
    form.resetFields();
    setModalOpen(true);
  };

  const openEdit = (record: Supplier) => {
    setEditing(record);
    form.setFieldsValue({ supplierName: record.supplierName, phone: record.phone, remark: record.remark });
    setModalOpen(true);
  };

  const handleSubmit = async () => {
    const values = await form.validateFields();
    if (editing) {
      await updateSupplier(editing.supplierId, values);
      message.success('更新成功');
    } else {
      await createSupplier(values);
      message.success('创建成功');
    }
    setModalOpen(false);
    actionRef.current?.reload();
  };

  const handleDelete = async (id: string) => {
    await deleteSupplier(id);
    message.success('删除成功');
    actionRef.current?.reload();
  };

  const handleToggleStatus = async (record: Supplier) => {
    await updateSupplier(record.supplierId, { status: record.status === 1 ? 0 : 1 });
    message.success('状态已更新');
    actionRef.current?.reload();
  };

  const columns: ProColumns<Supplier>[] = [
    { title: '供应商名称', dataIndex: 'supplierName' },
    { title: '联系电话', dataIndex: 'phone', search: false },
    { title: '采购次数', dataIndex: 'purchaseCount', search: false },
    { title: '累计入库数量', dataIndex: 'deliveredQty', search: false },
    { title: '应结金额', dataIndex: 'payableAmount', search: false },
    { title: '实结金额', dataIndex: 'paidAmount', search: false },
    {
      title: '状态',
      dataIndex: 'status',
      search: false,
      render: (_, r) => {
        const s = STATUS_MAP[r.status] ?? STATUS_MAP[1];
        return <Tag color={s.color}>{s.text}</Tag>;
      },
    },
    { title: '创建时间', dataIndex: 'createdAt', valueType: 'dateTime', search: false },
    {
      title: '操作',
      valueType: 'option',
      render: (_, r) => [
        <a key="edit" onClick={() => openEdit(r)}>编辑</a>,
        <a key="toggle" onClick={() => handleToggleStatus(r)}>
          {r.status === 1 ? '停用' : '启用'}
        </a>,
        <a key="del" style={{ color: '#ff4d4f' }} onClick={() => Modal.confirm({ title: '确认删除?', onOk: () => handleDelete(r.supplierId) })}>删除</a>,
      ],
    },
  ];

  return (
    <>
      <ProTable<Supplier>
        actionRef={actionRef}
        headerTitle="供应商管理"
        rowKey="supplierId"
        columns={columns}
        request={async (params) => {
          const res = await listSuppliers({ page: params.current, pageSize: params.pageSize, supplierName: params.supplierName });
          return { data: res?.data?.list || [], total: res?.data?.total || 0, success: res?.code === 0 };
        }}
        toolBarRender={() => [
          <Button key="add" type="primary" icon={<PlusOutlined />} onClick={openCreate}>新增供应商</Button>,
        ]}
      />
      <Modal
        title={editing ? '编辑供应商' : '新增供应商'}
        open={modalOpen}
        onOk={handleSubmit}
        onCancel={() => setModalOpen(false)}
        destroyOnClose
      >
        <Form form={form} layout="vertical">
          <Form.Item name="supplierName" label="供应商名称" rules={[{ required: true, message: '请输入供应商名称' }]}>
            <Input />
          </Form.Item>
          <Form.Item name="phone" label="联系电话">
            <Input />
          </Form.Item>
          <Form.Item name="remark" label="备注">
            <Input.TextArea rows={2} />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default SuppliersPage;
