import cc from 'classcat';
import { useLocalStorage } from 'hooks/useLocalStorage';

import { Box, Text } from 'components/common';
import { ErrorBoundary } from 'components/ErrorBoundary';
import { TreeViewToggle } from './TreeViewToggle';

interface SidebarSpoilerProps {
  title: string;
  disabled?: boolean;
  initialState?: boolean;
  className?: string;
  activeClassName?: string;
  style?: React.CSSProperties;
  children: React.ReactNode;
}

export const SidebarSpoiler = ({
  title,
  disabled,
  initialState = false,
  className,
  activeClassName = 'active',
  style,
  children,
  ...props
}: SidebarSpoilerProps) => {
  const [state, setState] = useLocalStorage(
    `SidebarPanel.${title}`,
    initialState
  );
  const show = !disabled && state;
  const cls = cc([
    'bg-white cup',
    className,
    { [activeClassName]: state, disabled },
  ]);

  return (
    <Box flex={state ? 'grow' : 'none'} {...props}>
      <Box
        className={cls}
        style={{ borderTop: '1px solid var(--borderColor)', ...style }}
        height={48}
        display="flex"
        align="center"
        justify="between"
        paddingX={2}
        onClick={() => setState(!state)}
      >
        <Box paddingX={1}>
          <Text weight="bold">{title}</Text>
        </Box>
        <TreeViewToggle state={show} />
      </Box>
      {show && <ErrorBoundary>{children}</ErrorBoundary>}
    </Box>
  );
};
