import { type FC } from 'react'
import { useFormik } from 'formik'
import * as Yup from 'yup'
import DefaulModal from '@/components/DefaulModal'
import Input from '@/components/Input'
import Button from '@/components/Button'
import { useCreateThemeValue } from '../hooks/useThemeData'
import { extractErrorMessage } from '@/helpers/utils'
import { toast } from 'react-toastify'
import { TickCircle } from 'iconsax-react'
import type { CreateThemeValueType } from '../type/Types'

interface Props {
  open: boolean
  close: () => void
  themeId: string
}

const CreateThemeValueModal: FC<Props> = ({ open, close, themeId }) => {
  const { mutate: createThemeValue, isPending } = useCreateThemeValue()

  const formik = useFormik<Omit<CreateThemeValueType, 'theme'>>({
    initialValues: {
      name: '',
      value: '',
    },
    validationSchema: Yup.object({
      name: Yup.string().required('نام الزامی است'),
      value: Yup.string().required('مقدار الزامی است'),
    }),
    onSubmit: (values) => {
      createThemeValue(
        {
          theme: themeId,
          name: values.name,
          value: values.value,
        },
        {
          onSuccess: () => {
            toast.success('مقدار تم با موفقیت ایجاد شد')
            formik.resetForm()
            close()
          },
          onError: (error) => {
            toast.error(extractErrorMessage(error))
          },
        }
      )
    },
  })

  const handleClose = () => {
    formik.resetForm()
    close()
  }

  return (
    <DefaulModal
      open={open}
      close={handleClose}
      isHeader
      title_header="افزودن مقدار تم"
    >
      <div className="mt-5 space-y-5 w-[400px]">
        <Input
          label="نام"
          placeholder="نام را وارد کنید"
          {...formik.getFieldProps('name')}
          error_text={
            formik.touched.name && formik.errors.name
              ? formik.errors.name
              : ''
          }
        />

        <Input
          label="مقدار"
          placeholder="مقدار را وارد کنید"
          {...formik.getFieldProps('value')}
          error_text={
            formik.touched.value && formik.errors.value
              ? formik.errors.value
              : ''
          }
        />

        <div className="flex gap-3 pt-3">
          <Button
            variant="outline"
            onClick={handleClose}
            disabled={isPending}
            className="w-fit"
          >
            انصراف
          </Button>
          <Button
            onClick={() => formik.handleSubmit()}
            isLoading={isPending}
            disabled={!formik.isValid || isPending}
            className="w-fit"
          >
            <div className="flex gap-2 items-center">
              <TickCircle size={16} color="#fff" />
              <div>ذخیره</div>
            </div>
          </Button>
        </div>
      </div>
    </DefaulModal>
  )
}

export default CreateThemeValueModal

