import { createMutation, createQuery, useQueryClient, } from "@tanstack/solid-query";
import AdminLayout from "../../admin-layout";
import { ErrorBoundary, For, Show, Suspense } from "solid-js";
import { A } from "@solidjs/router";
import { createPodcastMutation, readPodcastsOptions, readPodcastsQueryKey } from "../../client/@tanstack/solid-query.gen";
import Loading from "../../components/loading";
import Error from "../../components/error";
import { SERVER_URL } from "../../constants";
import { Eye, Plus } from "lucide-solid";
import { PodcastPublic } from "../../client";

export default function AdminPodcasts() {
  const queryClient = useQueryClient();

  const query = createQuery(() => ({
    ...readPodcastsOptions(),
  }));

  const createPodcast = createMutation(() => ({
    ...createPodcastMutation(),
    onSuccess(data) {
      queryClient.setQueryData(readPodcastsQueryKey(), (oldData: PodcastPublic[]) => oldData ? [...oldData, data] : oldData);
    },
  }));

  const createAction = () => {
    const name = prompt("Enter a podcast name");

    if (name != null && name.trim().length > 0) {
      createPodcast.mutate({
        body: {
          name,
          description: name
        }
      });
    }
  }

  return (
    <AdminLayout>
      <ErrorBoundary fallback={(err, reset) => <Error message={err} reset={reset} />}>
        <Suspense fallback={<Loading />}>
          <section class="section">
            <div class="container">
              <h1 class="title">Podcasts</h1>
              <div class="mb-4">
                <button class="button" onClick={() => createAction()}>
                  <Plus />
                  Create
                </button>
              </div>
              <For each={query.data}>
                {(podcast) => (
                  <div class="card">
                    <div class="card-content">
                      <div class="columns">
                        <Show when={podcast.image_filename}>
                          <div class="column">
                            <figure class="image is-64x64">
                              <img src={new URL(podcast.id + "/" + podcast.image_filename, SERVER_URL).href} />
                            </figure>
                          </div>
                        </Show>
                        <div class="column is-full">
                          <h5 class="title is-4">{podcast.name}</h5>
                          <p class="mb-4">{podcast.description}</p>
                          <A href={`/admin/${podcast.id}`} class="button"><Eye /> View</A>
                        </div>
                      </div>
                    </div>
                  </div>
                )}
              </For>
            </div>
          </section>
        </Suspense>
      </ErrorBoundary>
    </AdminLayout>
  );
}
