import type { mastodon } from "masto";
import { useTootEnv } from "../RegularToot";
import { Button } from "@suid/material";
import { Show } from "solid-js";
import {
  Bookmark,
  BookmarkAddOutlined,
  Repeat,
  ReplyAll,
  Share,
  Star,
  StarOutline,
} from "@suid/icons-material";
import { canShare, share } from "~platform/share";
import "./TootActionGroup.css";

async function shareContent(toot: mastodon.v1.Status) {
  return await share({
    url: toot.url ?? undefined,
  });
}

function isolatedCallback(e: MouseEvent) {
  e.stopPropagation();
}

function TootActionGroup<T extends mastodon.v1.Status>(props: {
  value: T;
  class?: string;
}) {
  const { reply, boost, favourite, bookmark } = useTootEnv();
  let actGrpElement: HTMLDivElement;
  const toot = () => props.value;
  return (
    <div
      ref={actGrpElement!}
      class={`TootActionGroup ${props.class || ""}`}
      onClick={isolatedCallback}
    >
      <Show when={reply}>
        <Button class="with-count" onClick={[reply!, props.value]}>
          <ReplyAll />
          <span>{toot().repliesCount}</span>
        </Button>
      </Show>

      <Button
        class="with-count"
        style={{
          color: toot().reblogged ? "var(--tutu-color-primary)" : undefined,
        }}
        onClick={[boost, props.value]}
      >
        <Repeat />
        <span>{toot().reblogsCount}</span>
      </Button>
      <Button
        class="with-count"
        style={{
          color: toot().favourited ? "var(--tutu-color-primary)" : undefined,
        }}
        onClick={[favourite, props.value]}
      >
        {toot().favourited ? <Star /> : <StarOutline />}
        <span>{toot().favouritesCount}</span>
      </Button>
      <Button
        class="plain"
        style={{
          color: toot().bookmarked ? "var(--tutu-color-primary)" : undefined,
        }}
        onClick={[bookmark, props.value]}
      >
        {toot().bookmarked ? <Bookmark /> : <BookmarkAddOutlined />}
      </Button>
      <Show when={canShare({ url: toot().url ?? undefined })}>
        <Button
          class="plain"
          aria-label="Share"
          onClick={[shareContent, toot()]}
        >
          <Share />
        </Button>
      </Show>
    </div>
  );
}

export default TootActionGroup;
