import { useEffect, useState } from 'react'
import { HelperText, Label, Select } from 'flowbite-react'

import formTheme from '@/lib/themes/form'
import { FollowUpRating } from '@/app/(dashboard)/follow-up-ratings/types'
import { getFollowUpRatings } from '@/lib/services/follow-up-rating-services'

interface FollowUpRatingSelectorProps {
  value?: number | string
  label?: string
  required?: boolean
  id?: string
  errorMessage?: string
  placeholder?: string
  fullWidth?: boolean
  onChange?: (rating: FollowUpRating | null) => void
}

export default function FollowUpRatingSelector({
  value,
  label = 'Rating',
  required = false,
  id = 'follow_up_rating_id',
  errorMessage,
  placeholder = '-- Select Rating --',
  fullWidth = false,
  onChange,
}: FollowUpRatingSelectorProps) {
  const [ratings, setRatings] = useState<FollowUpRating[]>([])

  const handleSelectionChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const selectedRating = ratings.find(
      (rating) => String(rating.id) === e.target.value,
    )
    onChange?.(selectedRating || null)
  }

  useEffect(() => {
    getFollowUpRatings({ all: true }).then((data) => {
      setRatings(data as FollowUpRating[])
    })
  }, [])

  return (
    <div className={fullWidth ? 'w-full' : 'w-full max-w-96'}>
      <div className="mb-2 block">
        <Label theme={formTheme.label} htmlFor={id}>
          {label} {required && <span className="text-red-500">*</span>}
        </Label>
      </div>
      <Select
        theme={formTheme.select}
        id={id}
        value={value ?? ''}
        onChange={handleSelectionChange}
        disabled={ratings.length === 0}
      >
        <option value="">{placeholder}</option>
        {ratings.map((rating) => (
          <option key={rating.id} value={rating.id}>
            {rating.label}
          </option>
        ))}
      </Select>
      {errorMessage && <HelperText color="failure">{errorMessage}</HelperText>}
    </div>
  )
}
