import Cookies from "js-cookie"

export const useCookies = () => {
  const setCookie = <T>(key: string, value: string | T, options?: Cookies.CookieAttributes) => {
    const expirationDate = new Date()
    expirationDate.setFullYear(expirationDate.getFullYear() + 10)
    const payload = typeof value === "string" ? value : JSON.stringify(value)
    Cookies.set(key, payload, {sameSite: "strict", expires: expirationDate, ...options})
  }

  const getCookie = <T = string>(key: string): T | null => {
    let value: T | null = null
    let cookie = ""
    try {
      cookie = Cookies.get(key) || ""
      value = JSON.parse(cookie) as T
    } catch (error) {
      if (!value) {
        value = cookie as T
      }
      // console.error(">>>>>>>>> Error in getCookie: ", error, value)
    }
    return value
  }

  const removeCookie = (key: string) => Cookies.remove(key)

  return {
    setCookie,
    getCookie,
    removeCookie,
  }
}
