import { useState } from "react";
/**
 * Custom hook for persisting state in local storage.
 *
 * This hook works similarly to the standard `useState` hook but also stores the state in local storage,
 * allowing the state to persist across browser sessions. The state is initialized from local storage
 * if it exists; otherwise, it falls back to the provided initial value.
 *
 * @template T The type of the value to be stored.
 * @param {string} key The key under which the value is stored in local storage.
 * @param {T} initialValue The initial value to be used if there is no item in local storage with the given key.
 * @returns {[T, (value: T | ((val: T) => T)) => void]} A tuple containing:
 *          - `storedValue`: the current value stored in local storage.
 *          - `setValue`: a function to set the value, which updates both the local state and local storage.
 *
 * @example
 * const [name, setName] = useLocalStorage<string>("name", "Initial Name");
 * // Use setName to update the name and it will be stored in local storage.
 */
const useLocalStorage = <T>(
	key: string,
	initialValue: T,
): [T, (value: T) => void] => {
	const [storedValue, setStoredValue] = useState<T>(() => {
		try {
			const item = window.localStorage.getItem(key);
			return item ? JSON.parse(item) : initialValue;
		} catch (error) {
			console.log(error);
			return initialValue;
		}
	});

	const setValue = (value: T) => {
		try {
			const valueToStore = value instanceof Function ? value(storedValue) : value;
			setStoredValue(valueToStore);
			window.localStorage.setItem(key, JSON.stringify(valueToStore));
		} catch (error) {
			console.log(error);
		}
	};

	return [storedValue, setValue];
};

export default useLocalStorage;
