import { LocationDescriptor, MeatballMenuApi } from "@heydovetail/ui-components";
import { ITag } from "@heydovetail/ui-components/lib.es2015/components/Highlighter";
import * as React from "react";
import { HighlightRange } from "../../range/types";
import { HighlightSidebarItem } from "./HighlightSidebarItem";

interface Props {
  highlights: (HighlightRange & { topOffset: number })[];
  width: number;
  tagLookup: Map<string, ITag>;

  generateTagURL: (tagId: string) => LocationDescriptor;
  onRemoveTag?: (options: { from: number; to: number; tagId: string }) => void;
  onCopyHighlightURL?: (rangeId: string) => void;
  onFocusRange: (rangeId: string | null) => void;
  tagQuickEditRenderer?: (tagId: string, menuApi: MeatballMenuApi) => React.ReactNode;
}

export class HighlightSidebar extends React.PureComponent<Props> {
  public render() {
    const {
      highlights,
      width,
      tagLookup,
      onRemoveTag,
      onCopyHighlightURL,
      onFocusRange,
      tagQuickEditRenderer,
      generateTagURL
    } = this.props;
    const TAG_HEIGHT = 28;
    const positionedHighlight = highlights.reduce(
      (accum, highlight) => {
        if (accum.currentOffset <= highlight.topOffset) {
          return {
            currentOffset: highlight.topOffset + TAG_HEIGHT * highlight.attrs.tagIds.length,
            highlights: [...accum.highlights, highlight]
          };
        } else {
          return {
            currentOffset: accum.currentOffset + TAG_HEIGHT * highlight.attrs.tagIds.length,
            highlights: [
              ...accum.highlights,
              {
                ...highlight,
                topOffset: accum.currentOffset
              }
            ]
          };
        }
      },
      { currentOffset: 0, highlights: [] as (HighlightRange & { topOffset: number })[] }
    );

    return (
      <div
        style={{
          width,
          position: "relative",
          height: "100%",
          visibility: width <= 100 ? "hidden" : undefined
        }}
      >
        {positionedHighlight.highlights.map(h => (
          <div key={h.id} style={{ position: "absolute", top: h.topOffset, width: "100%" }}>
            {h.attrs.tagIds.map(tagId => {
              const tag = tagLookup.get(tagId);
              return tag !== undefined ? (
                <HighlightSidebarItem
                  key={tag.id}
                  highlight={h}
                  tag={tag}
                  onRemoveTag={onRemoveTag}
                  onCopyHighlightURL={onCopyHighlightURL}
                  onFocusRange={onFocusRange}
                  tagQuickEditRenderer={tagQuickEditRenderer}
                  generateTagURL={generateTagURL}
                />
              ) : null;
            })}
          </div>
        ))}
      </div>
    );
  }
}
