import { h, Component, ComponentChildren } from 'preact';
import classes from './MarginalAnnotations.module.scss';
import cls from 'classnames';
import { AnnotationTargetHighlight } from './AnnotationTargetHighlight';
import type { IAnnotation, IAnnotationWithSource } from '../storage/Annotation';
import { WebAnnotation } from 'web-annotation-utils';

interface MarginalAnnotationsProps {
  appContainer: Node;
  annotations: IAnnotationWithSource[];
  annotationInFocus?: IAnnotationWithSource;
  toolbarButtons?: ComponentChildren;
  onUpdateAnnotation: (
    id: IAnnotation['_id'],
    newWebAnnotation: WebAnnotation,
  ) => Promise<void>;
  onDeleteAnnotation: (id: IAnnotation['_id']) => Promise<void>;
}

interface MarginalAnnotationsState {
  showAll: boolean;
}

export class MarginalAnnotations extends Component<
  MarginalAnnotationsProps,
  MarginalAnnotationsState
> {
  state: MarginalAnnotationsState = { showAll: false };

  toggleShowAll = () => {
    this.setState(({ showAll }) => ({ showAll: !showAll }));
  };

  render(
    {
      annotations,
      annotationInFocus,
      toolbarButtons,
      appContainer,
      onUpdateAnnotation,
      onDeleteAnnotation,
    }: MarginalAnnotationsProps,
    { showAll }: MarginalAnnotationsState,
  ) {
    const annotationElements = annotations.map((annotation) => (
      <AnnotationTargetHighlight
        key={annotation._id}
        annotation={annotation}
        appContainer={appContainer}
        inFocus={annotation._id === annotationInFocus?._id}
        onUpdateAnnotation={onUpdateAnnotation}
        onDeleteAnnotation={onDeleteAnnotation}
      />
    ));

    return (
      <div class={classes.annotationOuterContainer}>
        <div
          class={cls(classes.annotationContainer, {
            [classes.showAll]: showAll,
          })}
        >
          <div class={classes.toolbarContainer}>
            <div class={classes.toolbar}>
              {toolbarButtons}
              {(toolbarButtons || annotations.length > 0) && (
                <button
                  class={classes.showAllButton}
                  onClick={this.toggleShowAll}
                  title="Show/hide all annotations"
                >
                  {showAll ? '❯' : '❮'}
                </button>
              )}
            </div>
          </div>
          {annotationElements}
        </div>
      </div>
    );
  }
}
