import React, { useMemo } from 'react'
import { Select } from '@pikku/mantine/core'
import { useGetCountries } from '@/hooks/useGetCountries'

interface CountrySearchProps {
  value: string
  onChange: (value: string) => void
  error?: string
  label?: any
  placeholder?: any
}

export const CountrySearch: React.FunctionComponent<CountrySearchProps> = ({
  value,
  onChange,
  error,
  label,
  placeholder
}) => {
  const { data: countriesMap = {}, isLoading } = useGetCountries()

  const countryOptions = useMemo(() => {
    return Object.entries(countriesMap).map(([iso3, name]) => ({
      value: iso3,
      label: name
    }))
  }, [countriesMap])

  return (
    <Select
      label={label as any}
      value={value}
      data={countryOptions}
      onChange={(selectedValue) => onChange(selectedValue || '')}
      placeholder={placeholder as any}
      searchable
      error={error as any}
      disabled={isLoading && countryOptions.length === 0}
    />
  )
}
