import React, { useEffect } from 'react'
import { Form, Input, Modal } from 'antd'
import { decodeIfEncoded } from '@/utils/pass'

export type StaffFormValues = {
  name: string
  papers: string
  phone: string
  unit: string
}

type Props = {
  open: boolean
  editingStaff: Partial<StaffFormValues> | null
  onOk: (values: StaffFormValues) => void
  onCancel: () => void
}

function StaffModal({ open, editingStaff, onOk, onCancel }: Props) {
  const [form] = Form.useForm<StaffFormValues>()

  useEffect(() => {
    if (open) {
      if (editingStaff) {
        form.setFieldsValue({
          name: editingStaff.name ?? '',
          papers: decodeIfEncoded(editingStaff.papers ?? ''),
          phone: decodeIfEncoded(editingStaff.phone ?? ''),
          unit: editingStaff.unit ?? ''
        })
      } else {
        form.resetFields()
      }
    }
  }, [open, editingStaff, form])

  const handleOk = () => {
    form.validateFields().then(values => {
      onOk(values)
      form.resetFields()
    })
  }

  const handleCancel = () => {
    form.resetFields()
    onCancel()
  }

  return (
    <Modal
      destroyOnClose
      title={editingStaff ? '编辑人员' : '新增人员'}
      open={open}
      onOk={handleOk}
      onCancel={handleCancel}
      okText='确定'
      cancelText='取消'
    >
      <Form form={form} layout='vertical'>
        <Form.Item label='姓名' name='name' rules={[{ required: true, message: '请输入姓名' }]}>
          <Input placeholder='请输入姓名' maxLength={30} showCount />
        </Form.Item>
        <Form.Item label='证件信息' name='papers'>
          <Input placeholder='请输入证件信息' maxLength={30} showCount />
        </Form.Item>
        <Form.Item label='联系方式' name='phone'>
          <Input placeholder='请输入联系方式' maxLength={30} showCount />
        </Form.Item>
        <Form.Item label='所在单位' name='unit'>
          <Input placeholder='请输入所在单位' maxLength={30} showCount />
        </Form.Item>
      </Form>
    </Modal>
  )
}

export default StaffModal
