import { createDropzone } from "@soorria/solid-dropzone";
import { UploadIcon } from "lucide-solid";
import { createSignal, Show } from "solid-js";
import { createMutation, useQueryClient } from "@tanstack/solid-query";
import { episodeAdditionalUploadMutation, readEpisodesQueryKey, readEpisodeQueryKey } from "../client/@tanstack/solid-query.gen";
import { PodcastEpisodePublic } from "../client";

export default function UploadEpisodeAdditional(props: { podcastId: string, episodeId: string }) {
  const queryClient = useQueryClient();

  const [uploading, setUploading] = createSignal(false);
  const [statusText, setStatusText] = createSignal<string | null>(null);
  const uploadAdditional = createMutation(() => ({
    ...episodeAdditionalUploadMutation(),
    onSuccess(data, vars) {
      queryClient.setQueryData(readEpisodesQueryKey({ path: vars.path }), (oldData: PodcastEpisodePublic[]) => oldData ? [...oldData.filter((x) => x.id !== data.id), data] : oldData);
      queryClient.setQueryData(readEpisodeQueryKey({ path: vars.path }), data);
    }
  }))

  const dropzone = createDropzone({
    onDrop(files: File[]) {
      if (!files[0]) {
        throw new Error("No file was uploaded");
      }

      setStatusText("Uploading...");
      setUploading(true);

      uploadAdditional.mutate({
        body: {
          file: files[0],
        },
        path: {
          podcast_id: props.podcastId,
          episode_id: props.episodeId
        }
      }, {
        onSuccess() {
          setStatusText("Additional file uploaded!");
          setUploading(false);
        },
        onError(error, _variables, _context) {
          setStatusText(`Error uploading: ${error.detail}`);
          setUploading(false);
        },
      });
    }
  });

  return <>
    <Show when={statusText()}>
      <div class="notification is-info">
        {statusText()}
      </div>
    </Show>
    <Show when={!uploading()}>
      <div {...dropzone.getRootProps()} class="box is-flex is-flex-direction-column is-align-items-center p-6 mb-6">
        <input {...dropzone.getInputProps()} />
        <UploadIcon size="42" />
        <p class="mt-4 has-text-centered">
          {dropzone.isDragActive ? "Drop extra file here..." : "Drag an extra file here to upload, or click to open"}
        </p>
      </div>
    </Show>
  </>;
}
