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

import formTheme from '@/lib/themes/form'
import { getCountries } from '@/lib/services/country-services'

interface CountrySelectorProps {
  value?: number | string
  label?: string
  required?: boolean
  id?: string
  errorMessage?: string
  placeholder?: string
  onChange?: (country: Country | null) => void
}

export default function CountrySelector({
  value,
  label = 'Country',
  required = false,
  id = 'country',
  errorMessage,
  placeholder = '-- Select Country --',
  onChange,
}: CountrySelectorProps) {
  const [countries, setCountries] = useState<Country[]>([])

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

  useEffect(() => {
    getCountries().then((data) => {
      setCountries(data)
    })
  }, [])

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