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'
import { removeToken } from '../../helpers'
import { removeCookie } from '../../helpers/cookie'

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)
    removeToken()
    removeCookie('access_token')
    window.location.reload()
  }

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