import {
  Component,
  onCleanup,
  createSignal,
  Show,
  untrack,
  Match,
  Switch as JsSwitch,
  ErrorBoundary,
} from "solid-js";
import { type mastodon } from "masto";
import { Button, LinearProgress } from "@suid/material";
import { createTimeline } from "../masto/timelines";

import PullDownToRefresh from "./PullDownToRefresh";
import TootComposer from "./TootComposer";
import TootList from "./TootList";

const TimelinePanel: Component<{
  client: mastodon.rest.Client;
  name: "home" | "public";
  prefetch?: boolean;
}> = (props) => {
  const [scrollLinked, setScrollLinked] = createSignal<HTMLElement>();

  const [timeline, snapshot, { refetch: refetchTimeline }] = createTimeline(
    () => props.client.v1.timelines[props.name],
    () => ({ limit: 20 }),
  );

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

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

  return (
    <ErrorBoundary
      fallback={(err, reset) => {
        return <p>Oops: {String(err)}</p>;
      }}
    >
      <PullDownToRefresh
        linkedElement={scrollLinked()}
        loading={snapshot.loading}
        onRefresh={() => refetchTimeline("next")}
      />
      <div
        ref={(e) =>
          setTimeout(() => {
            setScrollLinked(e.parentElement!);
          }, 0)
        }
      >
        <Show when={props.name === "home"}>
          <TootComposer
            style={{
              "--scaffold-topbar-height": "0px",
            }}
            client={props.client}
            onSent={() => refetchTimeline("prev")}
          />
        </Show>

        <TootList
          threads={timeline.list}
          onUnknownThread={timeline.getPath}
          onChangeToot={timeline.set}
        ></TootList>
      </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, "next"]}
              disabled={snapshot.loading}
            >
              Retry
            </Button>
          </Match>
          <Match when={true}>
            <Button
              variant="contained"
              onClick={[refetchTimeline, "prev"]}
              disabled={snapshot.loading}
            >
              Load More
            </Button>
          </Match>
        </JsSwitch>
      </div>
    </ErrorBoundary>
  );
};

export default TimelinePanel;
