"use client";

import { useState, useEffect, useCallback } from "react";
import { logger } from "@/lib/logger";

/**
 * Hook for managing localStorage with SSR safety
 */
export function useLocalStorage<T>(
  key: string,
  initialValue: T
): [T, (value: T | ((val: T) => T)) => void, () => void] {
  // State to store our value
  const [storedValue, setStoredValue] = useState<T>(initialValue);
  const [isClient, setIsClient] = useState(false);

  // Check if we're on the client side
  useEffect(() => {
    setIsClient(true);
  }, []);

  // Get value from localStorage on client side
  useEffect(() => {
    if (!isClient) return;

    try {
      const item = window.localStorage.getItem(key);
      if (item) {
        const parsed: unknown = JSON.parse(item);
        setStoredValue(parsed as T);
      }
    } catch (error) {
      logger.warn("Error reading localStorage key", {
        key,
        error: error instanceof Error ? error.message : String(error),
      });
    }
  }, [key, isClient]);

  // Return a wrapped version of useState's setter function that persists the new value to localStorage
  const setValue = useCallback(
    (value: T | ((val: T) => T)) => {
      try {
        // Allow value to be a function so we have the same API as useState
        const valueToStore = value instanceof Function ? value(storedValue) : value;

        // Save state
        setStoredValue(valueToStore);

        // Save to localStorage if on client
        if (isClient) {
          window.localStorage.setItem(key, JSON.stringify(valueToStore));
        }
      } catch (error) {
        logger.warn("Error setting localStorage key", {
          key,
          error: error instanceof Error ? error.message : String(error),
        });
      }
    },
    [key, storedValue, isClient]
  );

  // Function to remove the item from localStorage
  const removeValue = useCallback(() => {
    try {
      setStoredValue(initialValue);
      if (isClient) {
        window.localStorage.removeItem(key);
      }
    } catch (error) {
      logger.warn("Error removing localStorage key", {
        key,
        error: error instanceof Error ? error.message : String(error),
      });
    }
  }, [key, initialValue, isClient]);

  return [storedValue, setValue, removeValue];
}
