import React, { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import { Box, MainButton, Switch, Text } from '@nova-hf/ui';

type FeatureFlag = { localStorageKey: string; isActive: boolean };

const featureFlags: FeatureFlag[] = [
  {
    localStorageKey: 'beta',
    isActive: false,
  },
  { localStorageKey: 'afslattur', isActive: false },
  { localStorageKey: 'crm', isActive: false },
  { localStorageKey: 'flokkar', isActive: false },
  { localStorageKey: 'mobileSignup', isActive: false },
  { localStorageKey: 'retthafi', isActive: false },
];

function getStorageValue(key: string, defaultValue: boolean) {
  if (typeof window !== 'undefined') {
    const saved = localStorage.getItem(key);
    const initial = saved !== null ? JSON.parse(saved) : defaultValue;
    return initial;
  }
}

const useLocalStorage = (key: string, defaultValue: boolean) => {
  const [value, setValue] = useState(() => {
    return getStorageValue(key, defaultValue);
  });

  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);

  return [value, setValue];
};

type StorageSwitchProps = {
  onToggle: () => void;
} & FeatureFlag;

const StorageSwitch = ({ localStorageKey, isActive, onToggle }: StorageSwitchProps) => {
  const [storageKey, setStorageKey] = useLocalStorage(localStorageKey, isActive);

  return (
    <Box display="inline-flex" gap={2}>
      <Switch
        isOn={storageKey === true}
        onToggle={() => {
          onToggle();
          return setStorageKey(storageKey === true ? false : true);
        }}
      />
      <Text variant="pMediumBold">{localStorageKey}</Text>
    </Box>
  );
};

export const FeatureFlags = () => {
  const [isDrawerOpen, setIsDrawerOpen] = useState(false);
  const [isButtonActive, setIsButtonActive] = useState(false);

  const handleKeyDown = (e: KeyboardEvent) => {
    if (e.ctrlKey && e.shiftKey && e.key === 'K') {
      setIsDrawerOpen((value) => !value);
    }
  };

  useEffect(() => {
    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, []);

  const flags = featureFlags.map((flag) => (
    <StorageSwitch
      key={flag.localStorageKey}
      localStorageKey={flag.localStorageKey}
      isActive={flag.isActive}
      onToggle={() => setIsButtonActive(true)}
    />
  ));

  return isDrawerOpen
    ? createPortal(
        <Box
          position="fixed"
          left={0}
          top={0}
          bottom={0}
          paddingY={8}
          paddingX={4}
          background="white"
          boxShadow="product"
          display="flex"
          flexDirection="column"
          justifyContent="space-between"
          style={{ zIndex: 2147483648 }}
        >
          <Box>
            <Text variant="h6" marginBottom={5}>
              Feature Flags:
            </Text>
            <Box display="flex" flexDirection="column" gap={4}>
              {flags}
            </Box>
          </Box>
          <MainButton
            icon="refresh"
            colorScheme="green"
            text="Reload"
            dottedShadow="none"
            onClick={() => window.location.reload()}
            isDisabled={!isButtonActive}
          />
        </Box>,
        document.getElementById('app')!,
      )
    : null;
};

export const getFeatureFlags = (): Record<string, boolean> => {
  const mappedFlags = featureFlags.map((flag) => {
    const value = getStorageValue(flag.localStorageKey, flag.isActive);
    return {
      ['key']: flag.localStorageKey,
      ['value']: value,
    };
  });
  return mappedFlags.reduce((obj, item) => Object.assign(obj, { [item.key]: item.value }), {});
};
