import { h, Component, ComponentChild } from 'preact';
import classes from './MarginalAnnotations.module.scss';
import type { backgroundRpcServer } from '../background';
import type { AnnotationSourceDescriptor } from '../storage/AnnotationSource';
import { RpcClient } from 'webextension-rpc';
import rssIcon from '../assets/icons/rss.svg';
import infoIcon from '../assets/icons/info.svg';
import downloadIcon from '../assets/icons/download.svg';

const backgroundRpc = new RpcClient<typeof backgroundRpcServer>();
const addAnnotationSource = backgroundRpc.func('addAnnotationSource');
const removeSource = backgroundRpc.func('removeSource');
const refreshAnnotationSource = backgroundRpc.func('refreshAnnotationSource');

interface ToolbarButtonsProps {
  discoveredSources: (AnnotationSourceDescriptor & { subscribed: boolean })[];
  onChange: () => void;
}

interface ToolbarButtonsState {
  showAll: boolean;
}

export class ToolbarButtons extends Component<
  ToolbarButtonsProps,
  ToolbarButtonsState
> {
  render(
    { discoveredSources, onChange }: ToolbarButtonsProps,
    {}: ToolbarButtonsState,
  ) {
    const buttons: ComponentChild[] = [];
    for (const source of discoveredSources) {
      let explanationSummary, explanationFull;
      if (source.type === 'container') {
        explanationSummary = (
          <span>
            <img src={rssIcon} /> This page provides an annotation source{' '}
            <i>“{source.title}”</i>. <img src={infoIcon} />
          </span>
        );
        explanationFull = `If you subscribe to it, annotations published by this website will be stored in your browser, and displayed on the web pages they target. Its annotations are automatically refreshed periodically.`;
      } else if (source.type === 'embeddedJsonld') {
        explanationSummary = (
          <span>
            This page contains embedded annotations. <img src={infoIcon} />
          </span>
        );
        explanationFull = `If you import them, they will be stored in your browser, and displayed on the web pages they target. Note they will not be refreshed automatically.`;
      }
      buttons.push(
        <details class={classes.hiddenWhenClosed}>
          <summary>{explanationSummary}</summary>
          {explanationFull}
        </details>,
      );

      if (source.subscribed) {
        if (source.type === 'container') {
          buttons.push(
            <button
              title="Unsubscribe from this annotation source (forget its annotations)"
              onClick={async () => {
                await removeSource(source);
                onChange();
              }}
            >
              ❌<span class={classes.hiddenWhenClosed}> Unsubscribe</span>
            </button>,
            <button
              title="Refresh annotations from this source."
              onClick={() => refreshAnnotationSource(source, true)}
            >
              🗘<span class={classes.hiddenWhenClosed}> Refresh</span>
            </button>,
          );
        } else if (source.type === 'embeddedJsonld') {
          buttons.push(
            <button
              title="Remove annotations from this source."
              onClick={async () => {
                await removeSource(source);
                onChange();
              }}
            >
              ❌<span class={classes.hiddenWhenClosed}> Remove</span>
            </button>,
            <button
              title="Refresh annotations from this source."
              onClick={() => refreshAnnotationSource(source, true)}
            >
              🗘<span class={classes.hiddenWhenClosed}> Refresh</span>
            </button>,
          );
        }
      } else {
        if (source.type === 'container') {
          buttons.push(
            <button
              onClick={async () => {
                await addAnnotationSource(source);
                onChange();
              }}
              title="Subscribe to annotations from this website."
            >
              <img src={rssIcon} class={classes.icon} />
              <span class={classes.hiddenWhenClosed}> Subscribe</span>
            </button>,
          );
        } else if (source.type === 'embeddedJsonld') {
          buttons.push(
            <button
              onClick={async () => {
                await addAnnotationSource(source);
                onChange();
              }}
              title="Import the annotations embedded in this page."
            >
              <img src={downloadIcon} class={classes.icon} />
              <span class={classes.hiddenWhenClosed}> Import annotations</span>
            </button>,
          );
        }
      }
    }
    return buttons.length > 0 ? buttons : null;
  }
}

// TODO Refresh components properly. instead of reload the whole page. :)
function pageReload() {
  window.location = window.location;
}
