import AsyncSelect from 'react-select/async'
import { useEffect, useRef, useState } from 'react'
import { InputActionMeta, MultiValue } from 'react-select'

import { SelectOption } from '@/src/interfaces/select'
import { useFetchStudyYears } from '@/src/hooks/user/studyYears'
import { debounce } from 'lodash'
import { useUserStore } from '@/src/store/userStore'
import { useFetchStudentStudyYear } from '@/src/hooks/user/studentStudyYears'

interface Props {
  onChange: (value: any) => void
}

export default function AsyncMultiSelectStudyYears({ onChange }: Props) {
  const { studentSelected } = useUserStore()
  const [optionsSelected, setOptionsSelected] = useState<SelectOption[]>([])
  const [defaultOptions, setDefaultOptions] = useState<SelectOption[]>([])
  const [searchText, setSearchText] = useState('')
  const setSearchTextDebounced = useRef(
    debounce(searchText => setSearchText(searchText), 500),
  ).current
  const [inputText, setInputText] = useState('')

  const { data: studyYearsSelected } = useFetchStudentStudyYear(
    studentSelected?.id || '',
  )
  const { data, isLoading, isFetching } = useFetchStudyYears({
    page: 1,
    sort: 'year:desc',
    pageSize: 5,
    search: searchText,
  })

  const handleChange = (options: MultiValue<SelectOption>) => {
    if (options) {
      setOptionsSelected([...options])
      onChange(options.map(option => option.value))
    }
  }

  const handleInputChange = (newValue: string, event: InputActionMeta) => {
    if (event.action !== 'input-blur' && event.action !== 'menu-close') {
      setSearchTextDebounced(newValue)
      setInputText(newValue)
      if (newValue) {
        setOptionsSelected([])
      }
    }
  }

  /* useEffect(() => {
    if (studyYearsData) {
      setStudyYearsOptions(
        studyYearsData.studyYears.map(studyYear => ({
          value: studyYear.id,
          label: studyYear.year,
        })),
      )
    }
  }, [studyYearsData]) */

  const handleLoadOptions = (
    inputValue: string,
    callback: (options: SelectOption[]) => void,
  ) => {
    setSearchTextDebounced(inputValue)
    /* refetch()
      .then(({ data }) => {
        callback(
          data?.studyYears.map(sy => ({
            value: sy.id,
            label: sy.year,
          })) ?? [],
        )
      })
      .catch(e => console.error(e)) */

    callback(
      data?.studyYears.map(sy => ({
        value: sy.id,
        label: sy.year,
      })) ?? [],
    )
  }

  useEffect(() => {
    setDefaultOptions(
      data?.studyYears.map(sy => ({ value: sy.id, label: sy.year })) ?? [],
    )
  }, [])

  useEffect(() => {
    if (studyYearsSelected) {
      const studyYearsOptions = studyYearsSelected.map(sy => ({
        value: sy.id,
        label: sy.year,
      }))
      setOptionsSelected(prevState =>
        studyYearsSelected ? [...prevState, ...studyYearsOptions] : [],
      )
    }
  }, [studyYearsSelected])

  return (
    <AsyncSelect
      isMulti
      closeMenuOnSelect={false}
      placeholder="Busque ciclos académicos"
      noOptionsMessage={() => 'No hay ciclos académicos'}
      value={optionsSelected}
      onChange={handleChange}
      isClearable={true}
      inputValue={inputText}
      isLoading={isLoading || isFetching}
      loadingMessage={() => 'Cargando...'}
      cacheOptions
      defaultOptions={defaultOptions}
      loadOptions={handleLoadOptions}
      onInputChange={handleInputChange}
      styles={{
        container: styles => ({
          ...styles,
          borderRadius: '0.5rem',
        }),
        control: styles => ({
          ...styles,
          padding: '2.5px',
          borderRadius: '0.5rem',
          backgroundColor: 'rgb(249 250 251 / var(--tw-bg-opacity))',
        }),
        multiValue: styles => ({
          ...styles,
          backgroundColor: '#c8cce0',
        }),
      }}
    />
  )
}
