import { useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { useQueryClient } from 'react-query'

import { useForm } from '@/src/hooks/useForm'
import { useModifyStudent } from '@/src/hooks/user/students'
import { StudentEditFormValues } from '@/src/interfaces/users/students'
import { validateEditStudent } from '@/src/validations/user'
import { useUIStore } from '@/src/store/uiStore'
import { useUserStore } from '@/src/store/userStore'

export const useEditStudentForm = (initialValues: StudentEditFormValues) => {
  const { setLoading } = useUIStore()
  const { studentSelected, clearStudentSelected } = useUserStore()

  const queryClient = useQueryClient()
  const router = useRouter()
  const { mutate, isLoading } = useModifyStudent()

  const { values, errors, setValues, handleChange, handleSubmit } = useForm(
    initialValues,
    validateEditStudent,
    values => {
      if (studentSelected) {
        mutate(
          { payload: values, id: studentSelected?.id },
          {
            onSuccess: () => {
              queryClient.invalidateQueries('students')
              clearStudentSelected()
              setValues(initialValues)
              router.push('/students')
            },
            onError: () => {
              clearStudentSelected()
              setValues(initialValues)
              router.push('/students')
            },
          },
        )
      } else {
        router.push('/students')
      }
    },
  )

  const handleSelectEnrollmentPromotion = (value: any) => {
    if (value) {
      setValues({ ...values, startedStudyYearId: value })
    }
  }

  const handleSelectStudyProgram = (value: any) => {
    if (value) {
      setValues({ ...values, studyProgramId: value })
    }
  }

  const handleSelectStudyYears = (value: any) => {
    if (value) {
      setValues({ ...values, studyYearIds: value })
    }
  }

  const handleSelectEnrollmentStatus = (value: any) => {
    if (value) {
      setValues({ ...values, enrollmentStatusId: value })
    }
  }

  const handleSelectGender = (value: any) => {
    if (value) {
      setValues({ ...values, gender: value })
    }
  }

  useEffect(() => {
    setValues({
      code: studentSelected?.code || initialValues.code,
      name: studentSelected?.name || initialValues.name,
      lastname: studentSelected?.lastname || initialValues.lastname,
      email: studentSelected?.email || initialValues.email,
      dni: studentSelected?.dni
        ? studentSelected?.dni.toString()
        : initialValues.dni,
      address: studentSelected?.address || initialValues.address,
      phone: studentSelected?.phone
        ? studentSelected?.phone.toString()
        : initialValues.phone,
      dateOfBirth: studentSelected?.dateOfBirth
        ? new Date(studentSelected?.dateOfBirth || '')
          .toISOString()
          .split('T')[0]
        : initialValues.dateOfBirth,
      gender: studentSelected?.gender || initialValues.gender,
      enrollmentStatusId:
        studentSelected?.enrollmentStatus.id ||
        initialValues.enrollmentStatusId,
      startedStudyYearId:
        studentSelected?.enrollmentPromotion.id ||
        initialValues.startedStudyYearId,
      studyProgramId:
        studentSelected?.studyProgram.id || initialValues.studyProgramId,
      studyYearIds:
        studentSelected?.studyYears.map(studyYear => studyYear.id) ||
        initialValues.studyYearIds,
      isActive: studentSelected?.isActive || initialValues.isActive,
    })
  }, [studentSelected])

  useEffect(() => {
    setLoading(isLoading)
  }, [isLoading])

  return {
    values,
    errors,
    setValues,
    handleChange,
    handleSubmit,
    handleSelectEnrollmentPromotion,
    handleSelectStudyProgram,
    handleSelectStudyYears,
    handleSelectEnrollmentStatus,
    handleSelectGender,
  }
}
