import { useCallback, useEffect, useState } from 'react';
import { LocalStorageEventListener } from 'src/application/models/localStorageEventListener';
import { LocalStorageKeys, useLocalStorage } from 'src/contexts/localStorageContext';

// Reactive localStorage value hook
export const useLocalStorageValue = (key: string) => {
  const { getItem, setItem, attachListener, detachListener } = useLocalStorage();
  const [value, setValue] = useState<string | null>(() => getItem(key));

  useEffect(() => {
    const listener: LocalStorageEventListener = {
      storageKey: key,
      listener: (event: StorageEvent) => {
        setValue(event.newValue);
      },
    };

    attachListener(listener);
    return () => detachListener(listener);
  }, [key, attachListener, detachListener]);

  const updateValue = useCallback(
    (newValue: string) => {
      setItem(key, newValue);
      setValue(newValue);
    },
    [key, setItem],
  );

  return { value, setValue: updateValue };
};

// Feature flag hook for Spiffy
export const useSpiffyFeatureFlag = () => {
  const { setSpiffyOnFeatureFlag } = useLocalStorage();
  const { value } = useLocalStorageValue(LocalStorageKeys.SpiffyOnOverride);

  const setFlag = useCallback(
    (flag: boolean | null) => {
      setSpiffyOnFeatureFlag(flag);
    },
    [setSpiffyOnFeatureFlag],
  );

  return {
    value: (() => {
      if (value === 'true') {
        return true;
      }
      if (value === 'false') {
        return false;
      }
      return null;
    })(),
    setFlag,
  };
};

// Feature flag hook for Envive
export const useEnviveFeatureFlag = () => {
  const { setItem, getItem } = useLocalStorage();
  const { value } = useLocalStorageValue(LocalStorageKeys.EnviveOnOverride);

  const setFlag = useCallback(
    (flag: boolean | null) => {
      if (flag === true) {
        setItem(LocalStorageKeys.EnviveOnOverride, 'true');
      } else if (flag === false) {
        setItem(LocalStorageKeys.EnviveOnOverride, 'false');
      }
    },
    [setItem],
  );

  return {
    value: (() => {
      if (value === 'true') {
        return true;
      }
      if (value === 'false') {
        return false;
      }
      return null;
    })(),
    setFlag,
  };
};

// Storage listener hook
export const useLocalStorageListener = (key: string, callback: (event: StorageEvent) => void) => {
  const { attachListener, detachListener } = useLocalStorage();

  useEffect(() => {
    const listener: LocalStorageEventListener = {
      storageKey: key,
      listener: callback,
    };
    attachListener(listener);
    return () => detachListener(listener);
  }, [key, callback, attachListener, detachListener]);
};
