/* 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, useQuery, useQueryClient } from 'react-query'
import { toast } from 'react-toastify'
import * as yup from 'yup'
import axios, { axiosErrorToast } from '../../../config/axios'
import ActionButton from '../../ActionButton'
import {
  FormDatePicker,
  FormSingleCheckbox,
  FormSingleSelect,
  FormTextField,
} from '../../HookForm'
import { createUpdateExperience } from '../service'

const schema = yup.object().shape({
  experienceType: yup.string().required('Experience type is required'),
  title: yup.string().required('Title is required'),
  organizationName: yup.string().required('Organization name is required'),
  fromDate: yup.string().required('From date is Required'),
  toDate: yup.string().when('currentlyWorking', {
    is: (val) => !val,
    then: yup.string().required('To date is Required'),
  }),
})

export const ExperienceForm = ({ data, hideDialog }) => {
  const queryClient = useQueryClient()

  const { data: types } = useQuery('experience-type', () =>
    axios.get('/square/experience/types').then((res) => res.data),
  )
  const { mutate, isLoading } = useMutation(createUpdateExperience, {
    onSuccess: () => {
      toast.success(data ? 'Experience Updated' : 'Experience Added')
      queryClient.invalidateQueries('dashboard')
      hideDialog()
    },
    onError: (err) => {
      console.log(err)
      axiosErrorToast(err)
    },
  })
  const { control, handleSubmit, watch } = useForm({
    resolver: yupResolver(schema),
    defaultValues: {
      ...data,
      fromDate: data ? moment(data.fromDate).toISOString() : '',
      toDate: data?.toDate ? moment(data.toDate).toISOString() : '',
    },
  })
  const onSubmit = (formData) => {
    const postBody = {
      ...formData,
      fromDate: moment(formData?.fromDate).format('YYYY-MM-DD'),
      toDate: currentlyWorking
        ? null
        : moment(formData.toDate).format('YYYY-MM-DD'),
    }
    mutate(postBody)
  }
  const onError = (error) => {
    console.log(error)
  }
  const selectedType = watch('experienceType')
  const currentlyWorking = watch('currentlyWorking')
  const isEmploymentType = selectedType === 'Employment'

  return (
    <form onSubmit={handleSubmit(onSubmit, onError)}>
      <Stack gap={2.5}>
        <FormSingleSelect
          name="experienceType"
          label={'Experience Type'}
          control={control}
          required
          options={types?.map((item) => ({
            value: item,
            label: item,
          }))}
        />
        {selectedType && (
          <>
            <FormTextField
              control={control}
              name="title"
              label={isEmploymentType ? 'Job Title' : `${selectedType} Title`}
              required
            />
            <FormTextField
              control={control}
              name="organizationName"
              label="Organisation Name"
              required
            />
            <FormSingleCheckbox
              control={control}
              name="currentlyWorking"
              label="Currently Working"
            />
            <Stack direction="row" gap={2}>
              <FormDatePicker
                control={control}
                name="fromDate"
                label="From"
                required
              />
              {!currentlyWorking && (
                <FormDatePicker
                  control={control}
                  name="toDate"
                  label="To"
                  required
                />
              )}
            </Stack>

            <FormTextField
              control={control}
              name="description"
              label="Description"
              multiline
              rows={4}
            />
          </>
        )}
      </Stack>
      <Stack direction="row" gap={2} mt={3}>
        <ActionButton type="submit" fullWidth loading={isLoading}>
          {data ? 'Edit Experience' : 'Add Experience'}
        </ActionButton>
        <ActionButton variant="outlined" fullWidth onClick={() => hideDialog()}>
          Cancel
        </ActionButton>
      </Stack>
    </form>
  )
}
