import { Client, CredentialManager } from "@atcute/client";
import { createResource, createSignal, For, Show } from "solid-js";
import { Button } from "../components/button";

const LIMIT = 1000;

const BlobView = (props: { pds: string; repo: string }) => {
  const [cursor, setCursor] = createSignal<string>();
  let rpc: Client;

  const fetchBlobs = async () => {
    if (!rpc) rpc = new Client({ handler: new CredentialManager({ service: props.pds }) });
    const res = await rpc.get("com.atproto.sync.listBlobs", {
      params: {
        did: props.repo as `did:${string}:${string}`,
        limit: LIMIT,
        cursor: cursor(),
      },
    });
    if (!res.ok) throw new Error(res.data.error);
    if (!res.data.cids) return [];
    setCursor(res.data.cids.length < LIMIT ? undefined : res.data.cursor);
    setBlobs(blobs()?.concat(res.data.cids) ?? res.data.cids);
    return res.data.cids;
  };

  const [response, { refetch }] = createResource(fetchBlobs);
  const [blobs, setBlobs] = createSignal<string[]>();

  return (
    <div class="flex flex-col items-center gap-2">
      <Show when={blobs() || response()}>
        <p>
          {blobs()?.length} blob{(blobs()?.length ?? 0 > 1) ? "s" : ""}
        </p>
        <div class="flex flex-col gap-0.5 font-mono text-sm wrap-anywhere lg:break-normal">
          <For each={blobs()}>
            {(cid) => (
              <a
                href={`${props.pds}/xrpc/com.atproto.sync.getBlob?did=${props.repo}&cid=${cid}`}
                target="_blank"
                class="rounded px-0.5 hover:bg-neutral-200 active:bg-neutral-300 dark:hover:bg-neutral-700 dark:active:bg-neutral-600"
              >
                <span class="text-blue-400">{cid}</span>
              </a>
            )}
          </For>
        </div>
      </Show>
      <Show when={cursor()}>
        <div class="dark:bg-dark-500 fixed bottom-0 z-5 flex w-screen justify-center bg-neutral-100 py-3">
          <Show when={!response.loading}>
            <Button onClick={() => refetch()}>Load More</Button>
          </Show>
          <Show when={response.loading}>
            <span class="iconify lucide--loader-circle animate-spin py-3.5 text-xl"></span>
          </Show>
        </div>
      </Show>
    </div>
  );
};

export { BlobView };
