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

import formTheme from '@/lib/themes/form'
import { AffiliateLevel } from '@/app/(dashboard)/affiliate-levels/types'
import { getAffiliateLevels } from '@/lib/services/affiliate-level-services'

interface AffiliateLevelSelectorProps {
  value?: number | string
  label?: string
  required?: boolean
  id?: string
  errorMessage?: string
  placeholder?: string
  onChange?: (affiliateLevel: AffiliateLevel | null) => void
}

export default function AffiliateLevelSelector({
  value,
  label = 'Affiliate Level',
  required = false,
  id = 'affiliate_level_id',
  errorMessage,
  placeholder = '-- Select Affiliate Level --',
  onChange,
}: AffiliateLevelSelectorProps) {
  const [affiliateLevels, setAffiliateLevels] = useState<AffiliateLevel[]>([])

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

  useEffect(() => {
    getAffiliateLevels({
      all: true,
    }).then((data) => {
      setAffiliateLevels(data as AffiliateLevel[])
    })
  }, [])

  return (
    <div>
      <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={affiliateLevels.length === 0}
      >
        <option value="">{placeholder}</option>
        {affiliateLevels.map((level) => (
          <option key={level.id} value={level.id}>
            {level.name}
          </option>
        ))}
      </Select>
      {errorMessage && <HelperText color="failure">{errorMessage}</HelperText>}
    </div>
  )
}
