import {
  Component,
  For,
  onCleanup,
  createSignal,
  Show,
  untrack,
  Match,
  Switch as JsSwitch,
  ErrorBoundary,
  createSelector,
} from "solid-js";
import { type mastodon } from "masto";
import { Button, LinearProgress } from "@suid/material";
import { createTimelineSnapshot } from "../masto/timelines.js";
import { vibrate } from "../platform/hardware.js";
import PullDownToRefresh from "./PullDownToRefresh.jsx";
import Thread from "./Thread.jsx";

const TrendTimelinePanel: Component<{
  client: mastodon.rest.Client;
  prefetch?: boolean;

  openFullScreenToot: (
    toot: mastodon.v1.Status,
    srcElement?: HTMLElement,
    reply?: boolean,
  ) => void;
}> = (props) => {
  const [scrollLinked, setScrollLinked] = createSignal<HTMLElement>();
  const [
    timeline,
    snapshot,
    { refetch: refetchTimeline, mutate: mutateTimeline },
  ] = createTimelineSnapshot(
    () => props.client.v1.trends.statuses,
    () => 120,
  );
  const [expandedId, setExpandedId] = createSignal<string>();

  const tlEndObserver = new IntersectionObserver(() => {
    if (untrack(() => props.prefetch) && !snapshot.loading)
      refetchTimeline({ direction: "old" });
  });

  onCleanup(() => tlEndObserver.disconnect());

  const isExpandedId = createSelector(expandedId);

  const isExpanded = (st: mastodon.v1.Status) => isExpandedId(st.id);

  const onBookmark = async (
    index: number,
    client: mastodon.rest.Client,
    status: mastodon.v1.Status,
  ) => {
    const result = await (status.bookmarked
      ? client.v1.statuses.$select(status.id).unbookmark()
      : client.v1.statuses.$select(status.id).bookmark());
    mutateTimeline((o) => {
      o![index] = [result];
      return o;
    });
  };

  const onBoost = async (
    index: number,
    client: mastodon.rest.Client,
    status: mastodon.v1.Status,
  ) => {
    const reblogged = status.reblog
      ? status.reblog.reblogged
      : status.reblogged;
    vibrate(50);
    mutateTimeline(index, (th) => {
      const x = th[0];
      if (x.reblog) {
        x.reblog = { ...x.reblog, reblogged: !reblogged };
        return [Object.assign({}, x)];
      } else {
        return [
          Object.assign({}, x, {
            reblogged: !reblogged,
          }),
        ];
      }
    });
    const result = reblogged
      ? await client.v1.statuses.$select(status.id).unreblog()
      : (await client.v1.statuses.$select(status.id).reblog()).reblog!;
    mutateTimeline(index, (th) => {
      Object.assign(th[0].reblog ?? th[0], {
        reblogged: result.reblogged,
        reblogsCount: result.reblogsCount,
      });
      return th;
    });
  };

  return (
    <ErrorBoundary
      fallback={(err, reset) => {
        return <p>Oops: {String(err)}</p>;
      }}
    >
      <PullDownToRefresh
        linkedElement={scrollLinked()}
        loading={snapshot.loading}
        onRefresh={() => refetchTimeline({ direction: "new" })}
      />
      <div
        ref={(e) =>
          setTimeout(() => {
            setScrollLinked(e.parentElement!);
          }, 0)
        }
      >
        <For each={timeline}>
          {(item, index) => {
            let element: HTMLElement | undefined;
            return (
              <Thread
                ref={element}
                toots={item}
                onBoost={(...args) => onBoost(index(), ...args)}
                onBookmark={(...args) => onBookmark(index(), ...args)}
                onReply={(client, status) =>
                  props.openFullScreenToot(status, element, true)
                }
                client={props.client}
                isExpended={isExpanded}
                onItemClick={(x) => {
                  if (x.id !== expandedId()) {
                    setExpandedId((o) => (o ? undefined : x.id));
                  } else {
                    props.openFullScreenToot(x, element);
                  }
                }}
              />
            );
          }}
        </For>
      </div>

      <div ref={(e) => tlEndObserver.observe(e)}></div>
      <Show when={snapshot.loading}>
        <div
          class="loading-line"
          style={{
            width: "100%",
          }}
        >
          <LinearProgress />
        </div>
      </Show>
      <div
        style={{
          display: "flex",
          padding: "20px 0 calc(20px + var(--safe-area-inset-bottom, 0px))",
          "align-items": "center",
          "justify-content": "center",
        }}
      >
        <JsSwitch>
          <Match when={snapshot.error}>
            <Button
              variant="contained"
              onClick={[refetchTimeline, undefined]}
              disabled={snapshot.loading}
            >
              Retry
            </Button>
          </Match>
          <Match when={true}>
            <Button
              variant="contained"
              onClick={[refetchTimeline, undefined]}
              disabled={snapshot.loading}
            >
              Refresh
            </Button>
          </Match>
        </JsSwitch>
      </div>
    </ErrorBoundary>
  );
};

export default TrendTimelinePanel;
