import { useContext } from 'react'

import { ToggleProviderContext } from '../../components/ToggleProvider/ToggleProvider'
import { hasValue } from '../../services/HelperServiceTyped'

/**
 * Shared utility to parse cookie value for a given key
 */
const parseCookieValue = (cookieString: string, key: string): string | null => {
  const cookies = cookieString.split(';')
  const toggleCookie = cookies.find((cookie) =>
    cookie.trim().startsWith(`${key}=`),
  )
  if (!toggleCookie) return null

  try {
    const [, value] = toggleCookie.trim().split('=', 2)
    return value ? decodeURIComponent(value) : null
  } catch (error) {
    // Return null for malformed cookies
    console.warn('Error parsing cookie value for key:', key, error)
    return null
  }
}

/**
 * Utility function to get toggle value from cookies (for server-side compatibility)
 */
export const getToggleFromCookie = (toggleKey: string): string | null => {
  if (typeof document === 'undefined') return null
  return parseCookieValue(document.cookie, toggleKey)
}

/**
 * Check if a toggle exists and is enabled (within the distribution/environment set by `ToggleProvider`)
 * The toggles from context already include cookie overrides merged by ToggleProvider
 *
 * @param toggleKeyToCheck The key of the toggle to check
 * @returns true if the given `toggleKeyToCheck` exists and is enabled for that distribution/environment
 */
export const useToggle = (toggleKeyToCheck: string): boolean => {
  const { toggles } = useContext(ToggleProviderContext)

  return !toggles || !Array.isArray(toggles)
    ? false
    : toggles.some((toggle) => {
        if (toggle.key === toggleKeyToCheck) {
          const cookieValue = getToggleFromCookie(toggleKeyToCheck)
          // Check if the cookie toggle is set and if it is, use it. If not, use the toggle from the original toggle.
          const cookieToggle = hasValue(cookieValue)
            ? cookieValue === 'true'
            : toggle.enabled
          return cookieToggle
        }
        return false
      })
}
