import { useEffect, useState } from 'react'
import { Modal, Form, Input, InputNumber, message, Spin } from 'antd'
import { itemApi } from '../services/api'

const MOBILE_BREAKPOINT = 768

function ItemForm({ visible, item, onSuccess, onCancel }) {
  const [form] = Form.useForm()
  const [submitting, setSubmitting] = useState(false)
  const [loading, setLoading] = useState(false)
  const [isMobile, setIsMobile] = useState(window.innerWidth < MOBILE_BREAKPOINT)
  const isEdit = !!item

  useEffect(() => {
    const handleResize = () => {
      setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
    }
    window.addEventListener('resize', handleResize)
    return () => window.removeEventListener('resize', handleResize)
  }, [])

  useEffect(() => {
    if (visible) {
      setLoading(true)
      if (item) {
        form.setFieldsValue({
          name: item.name,
          unit_price: item.unit_price
        })
      } else {
        form.resetFields()
      }
      setLoading(false)
    }
  }, [visible, item, form])

  const handleOk = async () => {
    try {
      const values = await form.validateFields()
      setSubmitting(true)
      
      if (isEdit) {
        await itemApi.update({ id: item.id, ...values })
        message.success('更新成功')
      } else {
        await itemApi.create(values)
        message.success('创建成功')
      }
      
      onSuccess()
    } catch (error) {
      if (error.errorFields) {
        return
      }
      message.error(error.message || '操作失败')
    } finally {
      setSubmitting(false)
    }
  }

  const validateName = (_, value) => {
    if (!value || !value.trim()) {
      return Promise.reject(new Error('请输入物品名称'))
    }
    return Promise.resolve()
  }

  const validateUnitPrice = (_, value) => {
    if (value === null || value === undefined || value === '') {
      return Promise.reject(new Error('请输入单价'))
    }
    if (typeof value !== 'number' || value <= 0) {
      return Promise.reject(new Error('单价必须是正数'))
    }
    return Promise.resolve()
  }

  return (
    <Modal
      title={isEdit ? '编辑物品' : '新增物品'}
      open={visible}
      onOk={handleOk}
      onCancel={onCancel}
      confirmLoading={submitting}
      okButtonProps={{ disabled: loading }}
      cancelButtonProps={{ disabled: submitting }}
      destroyOnClose
      okText="确定"
      cancelText="取消"
      width={isMobile ? '100%' : 520}
      style={isMobile ? { top: 20, maxWidth: 'calc(100vw - 32px)', margin: '0 auto' } : undefined}
    >
      <Spin spinning={loading}>
        <Form
          form={form}
          layout="vertical"
          autoComplete="off"
        >
          <Form.Item
            name="name"
            label="物品名称"
            rules={[{ validator: validateName }]}
          >
            <Input placeholder="请输入物品名称" maxLength={50} disabled={loading} />
          </Form.Item>
          <Form.Item
            name="unit_price"
            label="单价"
            rules={[{ validator: validateUnitPrice }]}
          >
            <InputNumber
              placeholder="请输入单价"
              min={0.01}
              step={0.01}
              precision={2}
              style={{ width: '100%' }}
              prefix="¥"
              disabled={loading}
            />
          </Form.Item>
        </Form>
      </Spin>
    </Modal>
  )
}

export default ItemForm
