'use client'

// React Imports
import { useState, useEffect, useCallback } from 'react'

const SENSOR_HUB_STORAGE_KEY = 'sensor_hub'

export interface SensorHubInfo {
  id: string
  [key: string]: unknown
}

export interface UseSensorHubReturn {
  /** Sensor hub data from localStorage */
  sensorHub: SensorHubInfo | null
  /** Whether sensor_hub exists in localStorage */
  hasSensorHub: boolean
  /** Save sensor hub to localStorage */
  setSensorHub: (data: SensorHubInfo | null) => void
  /** Get headers to attach to API requests (e.g. X-Sensor-Hub-Id) */
  getSensorHubHeaders: () => Record<string, string>
}

const parseSensorHub = (raw: string | null): SensorHubInfo | null => {
  if (!raw) return null
  try {
    const parsed = JSON.parse(raw)
    if (parsed && typeof parsed === 'object' && typeof parsed.id === 'string') {
      return parsed as SensorHubInfo
    }
  } catch {
    // ignore invalid JSON
  }
  return null
}

export const useSensorHub = (): UseSensorHubReturn => {
  const [sensorHub, setSensorHubState] = useState<SensorHubInfo | null>(null)

  useEffect(() => {
    if (typeof window === 'undefined') return
    const stored = localStorage.getItem(SENSOR_HUB_STORAGE_KEY)
    setSensorHubState(parseSensorHub(stored))
  }, [])

  const setSensorHub = useCallback((data: SensorHubInfo | null) => {
    if (typeof window === 'undefined') return
    if (data === null) {
      localStorage.removeItem(SENSOR_HUB_STORAGE_KEY)
      setSensorHubState(null)
    } else {
      localStorage.setItem(SENSOR_HUB_STORAGE_KEY, JSON.stringify(data))
      setSensorHubState(data)
    }
  }, [])

  const getSensorHubHeaders = useCallback((): Record<string, string> => {
    const hub = sensorHub ?? (typeof window !== 'undefined' ? parseSensorHub(localStorage.getItem(SENSOR_HUB_STORAGE_KEY)) : null)
    if (!hub?.id) return {}
    return {
      'X-Sensor-Hub-Id': hub.id
    }
  }, [sensorHub])

  return {
    sensorHub,
    hasSensorHub: sensorHub !== null,
    setSensorHub,
    getSensorHubHeaders
  }
}
