import {
  Button,
  Dialog,
  FormContainer,
  FormItem,
  Input,
  Notification,
  Select,
  toast,
} from '@/components/ui'
import { getMenuGroups } from '@/services/menu.service'
import { createTenantFromOrder } from '@/services/tenant.service'
import { SelectBoxOption } from '@/types/shared'
import { useLocalization } from '@/utils/hooks/useLocalization'
import { Field, FieldProps, Form, Formik, FormikHelpers } from 'formik'
import { useEffect, useState } from 'react'
import * as Yup from 'yup'

type CreateTenantFromOrderValues = {
  name: string
  menuGroup: string
}

type CreateTenantFromOrderDialogProps = {
  open: boolean
  onDialogClose: () => void
  orderId: string
}

const schema = Yup.object().shape({
  name: Yup.string().trim().required(),
  menuGroup: Yup.string().trim().required(),
})

const CreateTenantFromOrderDialog = ({
  open,
  onDialogClose,
  orderId,
}: CreateTenantFromOrderDialogProps) => {
  const { translate } = useLocalization()
  const [menuGroupOptions, setMenuGroupOptions] = useState<SelectBoxOption[]>([])
  const [isMenuGroupsLoading, setIsMenuGroupsLoading] = useState(false)

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

    const fetchMenuGroups = async () => {
      setIsMenuGroupsLoading(true)

      try {
        const response = await getMenuGroups()
        const items = response?.data ?? []

        setMenuGroupOptions(
          items.map((item: any) => ({
            value: String(item.key ?? item.Key ?? ''),
            label: String(item.name ?? item.Name ?? ''),
          })),
        )
      } catch {
        setMenuGroupOptions([])
      } finally {
        setIsMenuGroupsLoading(false)
      }
    }

    fetchMenuGroups()
  }, [open])

  const handleSubmit = async (
    values: CreateTenantFromOrderValues,
    { setSubmitting }: FormikHelpers<CreateTenantFromOrderValues>,
  ) => {
    setSubmitting(true)

    try {
      await createTenantFromOrder({
        orderId,
        name: values.name.trim(),
        menuGroup: values.menuGroup.trim(),
      })

      toast.push(
        <Notification type="success" duration={2500}>
          {translate('::App.Platform.Success') || 'Tenant kaydedildi'}
        </Notification>,
        { placement: 'bottom-end' },
      )

      onDialogClose()
    } catch (error) {
      const message =
        (error as any)?.response?.data?.error?.message ??
        (error as any)?.response?.data?.message ??
        (error as any)?.message ??
        'Islem basarisiz'

      toast.push(
        <Notification type="danger" duration={5000}>
          {message}
        </Notification>,
        { placement: 'bottom-end' },
      )
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <Dialog isOpen={open} onClose={onDialogClose} onRequestClose={onDialogClose}>
      <h5 className="mb-4">{translate('::App.Tenant.Create')}</h5>

      <Formik<CreateTenantFromOrderValues>
        initialValues={{
          name: '',
          menuGroup: 'Erp',
        }}
        validationSchema={schema}
        onSubmit={handleSubmit}
      >
        {({ errors, touched, isSubmitting }) => (
          <Form>
            <FormContainer>
              <FormItem
                label="Menu Group"
                invalid={Boolean(errors.menuGroup && touched.menuGroup)}
                errorMessage={errors.menuGroup}
              >
                <Field name="menuGroup">
                  {({ field, form }: FieldProps<string>) => (
                    <Select
                      field={field}
                      form={form}
                      isClearable={true}
                      isLoading={isMenuGroupsLoading}
                      options={menuGroupOptions}
                      value={menuGroupOptions.filter((option) => option.value === field.value)}
                      onChange={(option) => form.setFieldValue(field.name, option?.value ?? '')}
                    />
                  )}
                </Field>
              </FormItem>

              <FormItem
                label="Tenant Name"
                invalid={Boolean(errors.name && touched.name)}
                errorMessage={errors.name}
              >
                <Field name="name" component={Input} />
              </FormItem>

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

export default CreateTenantFromOrderDialog
