/** @jsx jsx */
import { jsx } from '@emotion/core';
import styled from '@emotion/styled';
import { gray100, gray200, gray300, gray600, blue500, gray700, gray800 } from '../../styles/colors_v2';
import { Fragment, useCallback, useContext, useEffect, useState } from 'react';
import { ScreenConfigurationContext } from '../../hooks/useScreenConfiguration';
import { CommandEditorContext, hasChanges, SaveableCommand } from '../../hooks/useCommandEditor';
import CommandEditor from './CommandEditor';
import CommandLibrary from './CommandLibrary';
import HeaderTab, { HeaderTabButton } from '../HeaderTab';
import HeaderTabTitle from '../HeaderTabTitle';
import { ReactComponent as XIcon } from '../../icons/X.svg';
import { ReactComponent as CaretUpIcon } from '../../icons/CaretUp.svg';
import { ReactComponent as CaretDownIcon } from '../../icons/CaretDown.svg';
import { ReactComponent as MenuIcon } from '../../icons/Menu.svg';
import { ClearButton } from '../../styles/elements';
import { commandSettingsWidth, navHeight } from '../../styles/dimensions';
import useKeyCommand, { Key as K } from '../../hooks/useKeyCommand';
import Modal, { ModalBody, ModalButton, ModalTitle } from '../../Modal';
import WalkthroughFlag from '../WalkthroughFlag';
import { WalkthroughContext, WalkthroughStep } from '../../hooks/useWalkthrough';

interface CodeWindowProps {
  visible: boolean;
}

const NewFileButton = styled(ClearButton)`
  color: ${gray600};
  font-size: 13px;
  padding: 6px;
  margin-right: 2px;
  margin-left: 30px;
  &:hover {
    color: ${blue500};
  }
`;

const CodeWindowWrapper = styled.div<{ visible: boolean }>`
  height: 100%;
  display: grid;
  grid-template-rows: 27px 20px 1fr;
  grid-template-columns: 1fr ${commandSettingsWidth}px;
  background: ${gray100};
  z-index: 2;
  opacity: ${({ visible }) => visible ? 1 : 0};
  pointer-events: ${({ visible }) => visible ? 'auto' : 'none'};
  position: relative;
  min-height: 0;
`;

const Boundary = styled.div`
  background-color: ${gray300};
  height: 27px;
  grid-column-start: 1;
  grid-column-end: 3;
  display: flex;
  align-items: stretch;
  justify-content: stretch;
`;

const ExpandContractButton = styled(ClearButton)`
  color: ${gray800};
  font-size: 13px;
  border-radius: 0;
  padding: 0 12px 0 3px;
  min-width: 180px;
  justify-content: flex-start;
  border-right: 1px solid ${gray200};
  svg {
    margin-right: 4px;
  }
  &:hover {
    color: ${gray800};
    background-color: ${gray600};
    cursor: pointer;
  }
`;

const RestOfBoundary = styled.div`
  display: flex;
  align-items: center;
  justify-content: center;
  flex-grow: 1;
  padding-right: 180px;
  svg {
    margin-top: -1px;
    * {
      fill: ${gray700};
    }
  }
  &:hover {
    background-color: ${gray600};
    cursor: grab;
  }
  &:active {
    cursor: grabbing;
  }
`;

const EditorHeader = styled.header<{ libraryView: boolean }>`
  display: flex;
  justify-content: space-between;
  ${({ libraryView }) => (
    libraryView
      ? `grid-column-start: 1; grid-column-end: 3; background-color: ${gray100};`
      : `grid-column-start: 1; grid-column-end: 2; background-color: ${gray100};`
  )}
`;

const TabList = styled.div`
  display: flex;
  justify-content: flex-start;
`;

const UnsavedDot = styled.div`
  width: 8px;
  height: 8px;
  margin-left: 10px;
  background-color: ${gray600};
  border-radius: 4px;
`;

const MenuIconWrap = styled.div`
  margin-top: 2px;
  padding: 0 0 0 8px;
`;

export default ({ visible }: CodeWindowProps) => {
  const screenConfiguration = useContext(ScreenConfigurationContext);
  const commandEditor = useContext(CommandEditorContext);
  const onClickExpandContract = useCallback(() => {
    if (screenConfiguration.commandViewHeight < 5) {
      screenConfiguration.setCommandViewHeight(75);
    } else {
      screenConfiguration.setCommandViewHeight(0);
    }
  }, [screenConfiguration]);

  useKeyCommand([K.Tilde], useCallback(() => {
    commandEditor.focusCommand(null);
    if (screenConfiguration.commandViewHeight < 5) {
      screenConfiguration.setCommandViewHeight(75);
    }
  }, [commandEditor, screenConfiguration]));

  const onBoundaryMouseDown = useCallback((e) => {
    const onMouseMove = (e: any) => {
      const effectiveHeight = e.clientY - (27 / 2);
      screenConfiguration.setCommandViewHeight(
        Math.min(1, Math.max(0, (1 - (effectiveHeight - navHeight) / (window.innerHeight - navHeight)))) * 100
      );
    }
    const onMouseUp = (e: any) => {
      window.removeEventListener('mouseup', onMouseUp);
      window.removeEventListener('mousemove', onMouseMove);
      document.body.className = "";
    }
    document.body.className = "no-select";
    window.addEventListener('mousemove', onMouseMove);
    window.addEventListener('mouseup', onMouseUp);
  }, [screenConfiguration]);

  const [commandToClose, setCommandToClose] = useState<SaveableCommand | null>(null);
  const onCloseCommand = useCallback(
    (command: SaveableCommand) => {
      if (hasChanges(command)) {
        setCommandToClose(command);
      } else {
        commandEditor.closeCommand(command);
      }
    },
    [setCommandToClose, commandEditor]
  );
  const onConfirmClose = useCallback(() => {
    if (commandToClose) {
      commandEditor.closeCommand(commandToClose);
      setCommandToClose(null);
    }
  }, [commandToClose, commandEditor]);

  const isVisible = screenConfiguration.commandViewHeight > 5;
  const walkthrough = useContext(WalkthroughContext);

  useEffect(() => {
    if (isVisible) {
      walkthrough.seeCommandRunner();
    }
  }, [isVisible, walkthrough]);

  return (
    <CodeWindowWrapper visible={visible}>
      {
        (!!commandToClose) && (
        <Modal maxWidth={400}>
          <ModalTitle>Are you sure?</ModalTitle>
          <ModalBody centered>"{commandToClose.name}" has unsaved changes.</ModalBody>
          <ModalButton onClick={() => setCommandToClose(null)}>Whoops. Cancel.</ModalButton>
          <ModalButton onClick={onConfirmClose}>That's ok. Close it.</ModalButton>
        </Modal>
      )}
      <Boundary>
        <WalkthroughFlag style={{ bottom: '100%' }} step={WalkthroughStep.OpenCommandRunner}>
          Expand the code editor to run effects &amp; audio generators!
        </WalkthroughFlag>
        <ExpandContractButton onClick={onClickExpandContract}>
          {
            screenConfiguration.commandViewHeight < 5
              ? <Fragment><CaretUpIcon /> Expand Code Editor</Fragment>
              : <Fragment><CaretDownIcon /> Hide Code Editor</Fragment>
          }
        </ExpandContractButton>
        <RestOfBoundary onMouseDown={onBoundaryMouseDown}>
          <MenuIcon />
        </RestOfBoundary>
      </Boundary>
      <EditorHeader libraryView={!commandEditor.focusedCommand}>
        <TabList>
          <HeaderTab
            active={commandEditor.focusedCommand === null}
            onClick={() => commandEditor.focusCommand(null)}
          >
            <MenuIconWrap><MenuIcon /></MenuIconWrap>
            <HeaderTabTitle value="Library (~)" />
          </HeaderTab>
          {commandEditor.commands.map((command, index) => (
            <HeaderTab
              key={index}
              active={command === commandEditor.focusedCommand}
              onClick={() => commandEditor.focusCommand(command)}
            >
              <HeaderTabButton onClick={(e) => { e.stopPropagation(); onCloseCommand(command); }}><XIcon /></HeaderTabButton>
              <HeaderTabTitle
                italicize={command === commandEditor.peekedCommand}
                value={command.name}
              />
              {hasChanges(command) && <UnsavedDot />}
            </HeaderTab>
          ))}
          <NewFileButton onClick={commandEditor.createNew}>
            + Open New
          </NewFileButton>
        </TabList>
      </EditorHeader>
      {!commandEditor.focusedCommand && <CommandLibrary />}
      {commandEditor.focusedCommand && <CommandEditor focusedCommand={commandEditor.focusedCommand} />}
    </CodeWindowWrapper>
  )
};
