import { useFetchRoles } from '@/src/hooks/user/roles'
import { SelectOption } from '@/src/interfaces/select'
import { useEffect, useState } from 'react'
import Select, { SingleValue } from 'react-select'

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

export default function SelectRole({ onChange, value }: Props) {
  const { data } = useFetchRoles()
  const [options, setOptions] = useState<SelectOption[]>([])

  useEffect(() => {
    if (data?.roles) {
      setOptions(
        data?.roles.map(role => ({ value: role.id, label: role.name })) ?? [],
      )
    }
  }, [data])

  const handleChange = (option: SingleValue<SelectOption>) => {
    if (option) {
      onChange(option.value)
    }
  }

  return (
    <Select
      placeholder="Seleccione rol de usuario"
      options={options}
      value={options.find(option => option.value === value)}
      onChange={handleChange}
      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',
        }),
      }}
    />
  )
}
