// NoteTypeSelect.js
import PropTypes from 'prop-types'
import { message, Tag, Select, Space } from 'antd'
import React, { useEffect, useState, useContext, useCallback } from 'react'
import axios from 'axios'
import { AuthContext } from '../context/AuthContext'
import config from '../../../config'

const NoteTypeSelect = ({ onChange, disabled, value = null }) => {
  const [noteTypeOptions, setNoteTypeOptions] = useState([])
  const [loading, setLoading] = useState(true)
  const [messageApi] = message.useMessage()

  const { authenticated } = useContext(AuthContext)

  const fetchNoteTypesData = useCallback(async () => {
    if (!authenticated) {
      return
    }
    setLoading(true)

    try {
      const response = await axios.get(
        `${config.backendUrl}/notetypes?active=true`,
        {
          headers: {
            Accept: 'application/json'
          },
          withCredentials: true // Important for including cookies
        }
      )
      const data = response.data

      setNoteTypeOptions(() => {
        var options = []
        data.map((noteType) => {
          var newNoteTypeOption = {
            label: (
              <Space>
                <Tag color={noteType?.color}>{noteType.name}</Tag>
              </Space>
            ),
            value: noteType._id
          }
          options.push(newNoteTypeOption)
        })
        return options
      })

      setLoading(false)
    } catch (error) {
      if (error.response) {
        // For other errors, show a message
        messageApi.error(
          'Error fetching note types data:',
          error.response.status
        )
      } else {
        messageApi.error(
          'An unexpected error occurred. Please try again later.'
        )
      }
    }
  }, [authenticated, messageApi])

  useEffect(() => {
    if (authenticated) {
      fetchNoteTypesData()
    }
  }, [authenticated, fetchNoteTypesData])

  return (
    <Select
      options={noteTypeOptions}
      onChange={onChange}
      loading={loading}
      disabled={disabled}
      placeholder='Select note type'
      style={{ width: '100%' }}
      value={value}
    />
  )
}

NoteTypeSelect.propTypes = {
  onChange: PropTypes.func,
  disabled: PropTypes.bool,
  checkable: PropTypes.bool,
  value: PropTypes.object
}

export default NoteTypeSelect
