import {
  Button,
  Dialog,
  FormContainer,
  FormItem,
  Input,
  Notification,
  toast,
} from '@/components/ui'
import { postMyNotificationByNotificationRuleId } from '@/services/notification.service'
import { useLocalization } from '@/utils/hooks/useLocalization'
import { Field, Form, Formik, FormikHelpers } from 'formik'
import * as Yup from 'yup'

export interface NotificationDto {
  id: string
  message: string
}

const scheme = Yup.object().shape({
  id: Yup.string().required(),
  message: Yup.string().required(),
})

function CreateNotification({
  open,
  onDialogClose,
  id,
}: {
  open: boolean
  onDialogClose: () => void
  id: string
}) {
  const { translate } = useLocalization()

  const handleSubmit = async (
    values: NotificationDto,
    { setSubmitting }: FormikHelpers<NotificationDto>,
  ) => {
    if (!id) {
      return
    }

    setSubmitting(true)

    try {
      await postMyNotificationByNotificationRuleId({ id, message: values.message })
      toast.push(
        <Notification type="success" duration={2000}>
          {translate('::Kaydet')}
        </Notification>,
        {
          placement: 'bottom-end',
        },
      )
      onDialogClose()
    } catch {
      toast.push(
        <Notification type="danger" duration={2000}>
          {'Hata'}
        </Notification>,
        {
          placement: 'bottom-end',
        },
      )
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <Dialog isOpen={open} onClose={onDialogClose} onRequestClose={onDialogClose}>
      <h5 className="mb-4">{id}</h5>
      <Formik initialValues={{ id, message: '' }} validationSchema={scheme} onSubmit={handleSubmit}>
        {({ touched, errors, isSubmitting }) => {
          return (
            <Form>
              <FormContainer size="sm">
                <FormItem
                  label="Message"
                  invalid={errors.message && touched.message}
                  errorMessage={errors.message}
                >
                  <Field
                    textArea="true"
                    type="text"
                    autoComplete="off"
                    name="message"
                    component={Input}
                  />
                </FormItem>

                <div className="mt-6 flex flex-row justify-end gap-3">
                  <Button size="sm" variant="solid" loading={isSubmitting} type="submit">
                    {isSubmitting ? translate('::Saving') : translate('::Save')}
                  </Button>
                  <Button size="sm" type="button" variant="plain" onClick={onDialogClose}>
                    {translate('::Cancel')}
                  </Button>
                </div>
              </FormContainer>
            </Form>
          )
        }}
      </Formik>
    </Dialog>
  )
}

export default CreateNotification
