import { urlTenantKey } from '../../contexts/Providers'
import { InstitutionsStore } from '../../shared-state/InstitutionsStore'
import { SearchSingleSelect } from '../Input/SearchSingleSelect'

export default function SchoolSwitch() {
  const { current, institutions } = InstitutionsStore.useState((s) => s)

  const handleChange = (value) => {
    if (value) {
      localStorage.setItem('institution_key', value?.value)
      window.location.replace(
        `${window.location.origin}/${urlTenantKey}/${value?.value}`,
      )
    }
  }
  const options =
    institutions?.map((item) => ({
      label: item?.name,
      value: item?.code,
    })) || []
  const selectedOption = { label: current?.name, value: current?.code }

  return (
    <SearchSingleSelect
      options={options}
      value={selectedOption}
      onChange={handleChange}
    />
  )
}
