import type { FormEvent } from 'react'

import {
  ENV,
  ENVType,
  isValidEnv,
} from 'config/env'
import { SELECTED_API_KEY } from 'helpers/selectedApi'

import { useToggle } from 'hooks/useToggle'
import { useLocalStore } from 'hooks/useStorage'

type FormElement = HTMLFormElement & {
  api: HTMLInputElement & {
    value: ENVType,
  },
}

export const useSystemSettings = () => {
  const {
    close,
    isOpen,
    open,
  } = useToggle()

  const [selectedApi, setSelectedApi] = useLocalStore({
    defaultValue: ENV,
    key: SELECTED_API_KEY,
    validator: isValidEnv,
  })

  const onSubmit = (e: FormEvent<FormElement>) => {
    e.preventDefault()

    const { api } = e.currentTarget
    setSelectedApi(api.value)
    window.location.reload()
  }

  return {
    close,
    isOpen,
    onSubmit,
    open,
    selectedApi,
  }
}
