import {
  Component,
  createSignal,
  Match,
  Switch as JsSwitch,
  ErrorBoundary,
} from "solid-js";
import { type mastodon } from "masto";
import { Button } from "@suid/material";
import { createTimelineSnapshot } from "../masto/timelines.js";
import PullDownToRefresh from "./PullDownToRefresh.jsx";
import TootList from "./TootList.jsx";

const TrendTimelinePanel: Component<{
  client: mastodon.rest.Client;
}> = (props) => {
  const [scrollLinked, setScrollLinked] = createSignal<HTMLElement>();
  const [tl, snapshot, { refetch: refetchTimeline }] = createTimelineSnapshot(
    () => props.client.v1.trends.statuses,
    () => ({ limit: 120 }),
  );

  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)
        }
      >
        <TootList
          threads={tl.list}
          onUnknownThread={tl.getPath}
          onChangeToot={tl.set}
        />
      </div>
      <div
        style={{
          display: "flex",
          padding: "20px 0 calc(20px + var(--safe-area-inset-bottom, 0px))",
          "align-items": "center",
          "justify-content": "center",
          "flex-flow": "column",
          gap: "20px",
        }}
      >
        <JsSwitch>
          <Match when={snapshot.error}>
            <p>{`Oops: ${snapshot.error}`}</p>
            <Button
              variant="contained"
              onClick={[refetchTimeline, undefined]}
              disabled={snapshot.loading}
            >
              Retry
            </Button>
          </Match>
        </JsSwitch>
      </div>
    </ErrorBoundary>
  );
};

export default TrendTimelinePanel;
