"use client"

import { useMemo, useState } from "react"
import { useFilter } from "react-aria-components"
import { useController, useFormContext } from "react-hook-form"
import { useIntl } from "react-intl"

import { Select } from "@scandic-hotels/design-system/Select"

import { countries } from "@/constants/countries"

import useLang from "@/hooks/useLang"

import ErrorMessage from "../ErrorMessage"

import type { CountryProps } from "./country"

export default function CountrySelect({
  className = "",
  label,
  name = "country",
  readOnly = false,
  registerOptions = {},
}: CountryProps) {
  const lang = useLang()
  const intl = useIntl()

  const { startsWith } = useFilter({ sensitivity: "base" })
  const [filterValue, setFilterValue] = useState("")
  const { control, setValue } = useFormContext()
  const { field, formState, fieldState } = useController({
    control,
    name,
    rules: registerOptions,
  })

  const items = useMemo(() => {
    const collator = new Intl.Collator(lang)
    return countries
      .map((country) => ({
        value: country.code,
        label:
          intl.formatDisplayName(country.code, { type: "region" }) ||
          country.name,
      }))
      .filter((item) => startsWith(item.label, filterValue))
      .sort((a, b) => collator.compare(a.label, b.label))
  }, [filterValue, intl, lang, startsWith])

  return (
    <div className={className}>
      <Select
        label={label}
        items={items}
        enableFiltering
        isRequired={Boolean(registerOptions?.required)}
        isInvalid={fieldState.invalid}
        name={field.name}
        onBlur={field.onBlur}
        onSelectionChange={(country) => setValue(name, country ?? "")}
        selectedKey={field.value}
        data-testid={name}
        isReadOnly={readOnly}
        onInputChange={setFilterValue}
      />
      <ErrorMessage errors={formState.errors} name={name} />
    </div>
  )
}
