import { Component, h, Fragment } from 'preact';
import classes from './AnnotationsList.module.scss';
import { Annotation } from '../storage/Annotation';
import { getTargetUrls } from 'web-annotation-utils';
import { IAnnotationSource } from '../storage/AnnotationSource';
import { AnnotationBody } from '../content_script/AnnotationBody';

interface AnnotationsListProps {
  source?: IAnnotationSource;
  withTotal?: boolean;
}

interface AnnotationsListState {
  annotations?: Annotation[];
  totalAnnotationCount?: number;
}

export class AnnotationsList extends Component<
  AnnotationsListProps,
  AnnotationsListState
> {
  state: AnnotationsListState = {};

  async componentDidMount() {
    await this.loadData();
  }

  async componentDidUpdate(previousProps: Readonly<AnnotationsListProps>) {
    if (
      previousProps.source?.lastModified !== this.props.source?.lastModified
    ) {
      this.loadData();
    }
  }

  async loadData() {
    let annotations;
    if (this.props.source) {
      if (this.props.source._id === undefined)
        throw new Error(`Got source without an _id`);
      annotations = await Annotation.getAnnotationsFromSource(
        this.props.source._id,
      );
    } else {
      annotations = await Annotation.getAll();
    }
    this.setState({ annotations });
  }

  render(
    { withTotal }: AnnotationsListProps,
    { annotations }: AnnotationsListState,
  ) {
    const annotationList = annotations?.map((annotation) => {
      const webAnnotation = annotation.data.annotation;
      return (
        <li class={classes.annotationWrapper} key={annotation.data._id}>
          <div class={classes.annotationBody}>
            <AnnotationBody
              body={webAnnotation.body}
              bodyValue={webAnnotation.bodyValue}
            />
          </div>
          <div>
            On:{' '}
            {getTargetUrls(webAnnotation.target).map((url) => (
              <><a href={url}>{url}</a>{' '}</>
            ))}
          </div>
          {' '}
          {/* <div class={classes.viewAsJson}>
            <a target="_blank" href={`data:application/json,${encodeURIComponent(JSON.stringify(annotation.data.annotation, null, 2))}`}>View annotation JSON</a>
          </div> */}
        </li>
      );
    });

    return (
      <>
        {annotationList ? (
          <ul class={classes.annotationList}>{annotationList}</ul>
        ) : (
          <p>
            <i>Loading…</i>
          </p>
        )}
        {withTotal && (
          <p>Total: {this.state.annotations?.length ?? <i>'counting…'</i>}</p>
        )}
      </>
    );
  }
}
