import { Form, Input, message, Modal, Select } from 'antd'
import React, { useEffect, useRef } from 'react'

import { notifyK8sUpgradeTask } from 'apiClient/services/devops'
import { ApiErrCode } from 'apiClient/services/devops/interface'

export const NOTIFY_CHANNEL_OPTIONS = [
  { label: 'Lark Group', value: 'lark_group' },
  { label: 'Email', value: 'email' }
] as const

export type NotifyChannel = (typeof NOTIFY_CHANNEL_OPTIONS)[number]['value']

type FormValues = {
  channels: NotifyChannel[]
  custom_message?: string
}

type NotifyUpgradeModalProps = {
  taskId: number | null
  loading?: boolean
  onLoadingChange?: (loading: boolean) => void
  onSuccess?: () => void
  onCancel: () => void
}

export const NotifyUpgradeModal: React.FC<NotifyUpgradeModalProps> = ({
  taskId,
  loading,
  onLoadingChange,
  onSuccess,
  onCancel
}) => {
  const [form] = Form.useForm<FormValues>()
  const submittingRef = useRef(false)

  useEffect(() => {
    if (taskId != null) {
      submittingRef.current = false
      onLoadingChange?.(false)
      form.setFieldsValue({
        channels: ['lark_group'],
        custom_message: undefined
      })
    }
  }, [form, onLoadingChange, taskId])

  const handleOk = async () => {
    if (taskId == null) return

    if (submittingRef.current) {
      return Promise.reject()
    }

    submittingRef.current = true
    onLoadingChange?.(true)

    try {
      const values = await form.validateFields()
      const resp = await notifyK8sUpgradeTask(taskId, {
        channels: values.channels,
        custom_message: values.custom_message?.trim() || undefined
      })
      if (resp.data.errcode && resp.data.errcode !== ApiErrCode.OK) {
        throw new Error(
          resp.data.errmsg || 'Failed to send upgrade notification'
        )
      }
      onSuccess?.()
      onCancel()
    } catch (e: any) {
      if (e?.errorFields) {
        throw e
      }
      message.error(
        e?.response?.data?.errmsg ||
          e?.response?.data?.message ||
          e?.message ||
          'Failed to send upgrade notification'
      )
      throw e
    } finally {
      submittingRef.current = false
      onLoadingChange?.(false)
    }
  }

  return (
    <Modal
      visible={taskId != null}
      title={
        taskId != null
          ? `Send Upgrade Notification (Task ${taskId})`
          : 'Send Upgrade Notification'
      }
      okText="Send"
      cancelText="Cancel"
      confirmLoading={loading}
      okButtonProps={{ disabled: loading }}
      cancelButtonProps={{ disabled: loading }}
      maskClosable={!loading}
      onOk={handleOk}
      onCancel={onCancel}
      destroyOnClose
    >
      <Form form={form} layout="vertical" preserve={false}>
        <Form.Item
          label="Notification Channels"
          name="channels"
          rules={[
            {
              required: true,
              type: 'array',
              min: 1,
              message: 'Please select at least one notification channel'
            }
          ]}
        >
          <Select
            mode="multiple"
            options={[...NOTIFY_CHANNEL_OPTIONS]}
            placeholder="Select notification channels"
          />
        </Form.Item>
        <Form.Item label="Additional Message" name="custom_message">
          <Input.TextArea
            rows={4}
            placeholder="Optional. Prepended to the notification content."
            allowClear
          />
        </Form.Item>
      </Form>
    </Modal>
  )
}
