import { useEffect, useState } from 'react'
import { Form, Input, Modal, Select, message } from 'antd'
import { getErrorMessage, isFormValidationError } from '@/lib/errors'
import { createWebhook, updateWebhook } from '@/services/webhooks'
import { WebhookEventText, type Webhook } from '@/types/webhook'

interface WebhookFormModalProps {
  open: boolean
  webhook: Webhook | null
  onSuccess: () => void
  onClose: () => void
}

export function WebhookFormModal({ open, webhook, onSuccess, onClose }: WebhookFormModalProps) {
  const [form] = Form.useForm()
  const [loading, setLoading] = useState(false)
  const isEdit = Boolean(webhook)

  useEffect(() => {
    if (!open) {
      return
    }

    if (webhook) {
      form.setFieldsValue({
        name: webhook.name,
        url: webhook.url,
        events: webhook.events,
      })
      return
    }

    form.resetFields()
  }, [form, open, webhook])

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields()
      setLoading(true)

      if (isEdit && webhook) {
        await updateWebhook(webhook.id, {
          name: values.name,
          url: values.url,
          events: values.events,
        })
        message.success('Webhook 已更新')
      } else {
        await createWebhook({
          name: values.name,
          url: values.url,
          secret: values.secret,
          events: values.events,
        })
        message.success('Webhook 已创建')
      }

      onSuccess()
    } catch (err) {
      if (isFormValidationError(err)) {
        return
      }
      message.error(getErrorMessage(err, '保存 Webhook 失败'))
    } finally {
      setLoading(false)
    }
  }

  const eventOptions = Object.entries(WebhookEventText).map(([value, label]) => ({
    value,
    label,
  }))

  return (
    <Modal
      title={isEdit ? '编辑 Webhook' : '创建 Webhook'}
      open={open}
      onOk={() => void handleSubmit()}
      onCancel={onClose}
      confirmLoading={loading}
      width={640}
    >
      <Form form={form} layout="vertical" initialValues={{ events: [] }}>
        <Form.Item
          name="name"
          label="Webhook 名称"
          rules={[
            { required: true, message: '请输入 Webhook 名称' },
            { max: 100, message: '名称不能超过 100 个字符' },
          ]}
        >
          <Input placeholder="例如：用户事件通知" />
        </Form.Item>

        <Form.Item
          name="url"
          label="目标 URL"
          rules={[
            { required: true, message: '请输入目标 URL' },
            { type: 'url', message: '请输入有效的 URL' },
          ]}
        >
          <Input placeholder="https://example.com/webhook" />
        </Form.Item>

        {!isEdit && (
          <Form.Item name="secret" label="签名密钥" extra="可选。不传则由后端生成。">
            <Input.Password placeholder="可选" />
          </Form.Item>
        )}

        <Form.Item
          name="events"
          label="订阅事件"
          rules={[{ required: true, message: '请至少选择一个事件' }]}
        >
          <Select mode="multiple" options={eventOptions} placeholder="选择事件类型" />
        </Form.Item>
      </Form>
    </Modal>
  )
}
