import { Box, Card, Group, Stack, Typography } from '@tidbcloud/uikit'
import { Button, Drawer, message, FormInstance, Form, Modal } from 'antd'
import dayjs from 'dayjs'
import { EditorState, convertToRaw } from 'draft-js'
import draftToHtml from 'draftjs-to-html'
import React, { useState } from 'react'
import useProfileContext from 'useProfileContext'

import {
  useBroadcastTrigger,
  useBulkTrigger
} from 'apiClient/services/notification'

import { FormType } from './NotificationDetail'
import { TypeIcon } from './TypeIcon'

export const NotificationSchedule = ({
  form,
  orgType,
  trigger,
  editorState,
  onSave
}: {
  form: FormInstance<FormType>
  orgType: 'target' | 'all'
  trigger: React.ReactElement
  editorState?: EditorState
  onSave: (values: FormType) => Promise<void>
}) => {
  const [testDrawerOpen, setTestDrawerOpen] = useState(false)

  const [loading, setLoading] = useState(false)

  const { mutateAsync: scheduleMutateAsync } = useBulkTrigger()

  const { mutateAsync: broadcastAsync } = useBroadcastTrigger()

  const {
    profile: { userEmail }
  } = useProfileContext()

  const formValues = form.getFieldsValue()

  const scheduleOrSendNow = formValues.is_send_now ? 'Send' : 'Schedule'

  const hideDrawer = () => {
    setTestDrawerOpen(false)
  }

  const handleTriggerClick = async () => {
    try {
      await form.validateFields()
      setTestDrawerOpen(true)
    } catch (err) {
      console.warn('Validate failed:', err)
    }
  }

  const onSchedule = async () => {
    setLoading(true)
    try {
      await onSave(form.getFieldsValue())
      const data = form.getFieldsValue()
      data.operator = userEmail
      if (orgType === 'all') {
        await broadcastAsync({ data })
      } else {
        await scheduleMutateAsync({ data })
      }
      message.success('Successfully schedule')
    } catch (e) {
      console.error(e)
      message.error('Failed to schedule')
    } finally {
      setLoading(false)
    }
  }

  const handleReviewClick = () => {
    if (!editorState) return
    let tpl = draftToHtml(convertToRaw(editorState.getCurrentContent())) || ''
    formValues.payload &&
      Object.entries(formValues.payload as {}).map(([k, v]) => {
        tpl = tpl?.replaceAll(`{{${k}}}`, v as string)
      })

    Modal.info({
      width: '100%',
      icon: null,
      content: (
        <Card>
          <Stack gap={24}>
            <Group>
              <TypeIcon type={formValues?.notification_group || ''} />
              <Box>
                <Typography variant="title-lg">
                  {formValues?.worker_flow_name}
                </Typography>
                <Typography variant="body-sm" c="gray.6">
                  {(formValues.schedule_time
                    ? dayjs(formValues.schedule_time)
                    : dayjs()
                  ).format('YYYY-MM-DD HH:mm:ss')}
                </Typography>
              </Box>
            </Group>
            <Box dangerouslySetInnerHTML={{ __html: tpl || '' }} />
          </Stack>
        </Card>
      )
    })
  }

  return (
    <>
      {React.cloneElement(trigger, { onClick: handleTriggerClick })}
      <Drawer
        title={`Review and ${scheduleOrSendNow}`}
        width={520}
        closable={false}
        onClose={hideDrawer}
        visible={testDrawerOpen}
      >
        <h3>Recipients</h3>
        <Form.Item label="Notification Name">
          <div>{formValues.worker_flow_name}</div>
        </Form.Item>
        <Form.Item label="Org ID">
          <div>{formValues.target_id_list?.join(',')}</div>
        </Form.Item>
        <Form.Item label="Target User Role">
          <div>{formValues.roles?.join(',')}</div>
        </Form.Item>
        <Button
          type="primary"
          htmlType="submit"
          loading={loading}
          style={{ marginRight: '12px' }}
          onClick={onSchedule}
        >
          {scheduleOrSendNow}
        </Button>
        <Button onClick={handleReviewClick} style={{ marginRight: '12px' }}>
          Review
        </Button>
        <Button onClick={hideDrawer}>Cancel</Button>
      </Drawer>
    </>
  )
}
