/* eslint-disable no-console */
import { yupResolver } from '@hookform/resolvers/yup'
import { Stack } from '@mui/material'
import moment from 'moment'
import { useForm } from 'react-hook-form'
import { useMutation, useQueryClient } from 'react-query'
import { toast } from 'react-toastify'
import * as yup from 'yup'
import { axiosErrorToast } from '../../../config/axios'
import ActionButton from '../../ActionButton'
import { FormDatePicker, FormTextField } from '../../HookForm'
import { createUpdateEducation } from '../service'

const schema = yup.object().shape({
  name: yup.string().required('Name is required'),
  institution: yup.string().required('Institution is required'),
  startDate: yup.string().nullable().required('From Date is required'),
  endDate: yup
    .string()

    .required('End Date is required')
    .test(
      'endDate',
      'To date must be greater than  From date',
      function (value) {
        const { startDate } = this.parent
        if (!startDate) return true
        const startDateObj = new Date(startDate)
        const endDateObj = new Date(value)
        return startDateObj < endDateObj
      },
    ),
  description: yup.string().required('Description is required'),
})

export const EducationForm = ({ data, hideDialog }) => {
  const queryClient = useQueryClient()
  const { mutate, isLoading } = useMutation(createUpdateEducation, {
    onSuccess: () => {
      toast.success(data ? 'Education Updated' : 'Education Added')
      queryClient.invalidateQueries('dashboard')
      hideDialog()
    },
    onError: (err) => {
      console.log(err)
      axiosErrorToast(err)
    },
  })
  const { control, handleSubmit } = useForm({
    resolver: yupResolver(schema),
    defaultValues: {
      ...data,
      startDate: data ? moment(data.startDate).toISOString() : '',
      endDate: data ? moment(data.endDate).toISOString() : '',
    },
  })
  const onSubmit = (formData) => {
    const postBody = {
      ...formData,
      startDate: moment(formData?.startDate).format('YYYY-MM-DD'),
      endDate: moment(formData.endDate).format('YYYY-MM-DD'),
    }
    mutate(postBody)
  }
  const onError = (error) => {
    console.log(error)
  }

  return (
    <form onSubmit={handleSubmit(onSubmit, onError)}>
      <Stack gap={2.5}>
        <>
          <FormTextField
            control={control}
            name="name"
            label="Name of the education"
            required
          />
          <FormTextField
            control={control}
            name="institution"
            label="Institution"
            required
          />
          <Stack direction="row" gap={2}>
            <FormDatePicker
              control={control}
              name="startDate"
              label="From Date"
              required
            />
            <FormDatePicker
              control={control}
              name="endDate"
              label="To Date"
              required
            />
          </Stack>
          <FormTextField
            control={control}
            multiline
            rows={4}
            name="description"
            label="Description"
            required
          />
        </>
      </Stack>
      <Stack direction="row" gap={2} mt={3}>
        <ActionButton type="submit" fullWidth loading={isLoading}>
          Submit
        </ActionButton>
        <ActionButton variant="outlined" fullWidth onClick={() => hideDialog()}>
          Cancel
        </ActionButton>
      </Stack>
    </form>
  )
}
