import { component$, useVisibleTask$ } from "@builder.io/qwik";
import { useDropzone } from "~/hooks/dropzone";
import { useNanostore$ } from "~/hooks/nanostores";
import { api } from "~/lib/api";
import { dashboardFiles } from "~/lib/stores";
import { StereoFile } from "~/lib/types";

export default component$(() => {
	const dashfiles = useNanostore$<StereoFile[]>(dashboardFiles);
	
  const {
	highlight,
	onDragOver,
	onDragLeave,
	onInputChange,
	triggerFileInput,
	fileInputRef,
  } = useDropzone();

  useVisibleTask$(() => {
	const dropzone = document.getElementById("dropzone");
	if (!dropzone) return;
	const handler = async (e: DragEvent) => {
	  e.preventDefault();
	  highlight.value = false;
	  const files = Array.from(e.dataTransfer?.files || []);
	  for (const file of files) {
		const name = file.name.replace(/[^a-zA-Z0-9_.-]/g, "_");
		const f = new File([file], name, { type: file.type });
		await api.upload(f);
		dashfiles.value = await api.list();
	  }
	};
	dropzone.addEventListener("drop", handler);
	return () => dropzone.removeEventListener("drop", handler);
  });

  return (
	<div
	  id="dropzone"
	  preventdefault:drop
	  class={{
		"relative z-10 border-2 border-dashed rounded-lg p-10 transition-colors": true,
		"border-white bg-black/20": highlight.value,
		"border-neutral-800": !highlight.value,
	  }}
	  onDragOver$={onDragOver}
	  onDragLeave$={onDragLeave}
	  onClick$={triggerFileInput}
	>
	  <p class="text-center text-neutral-500 pointer-events-none">drop file ehre</p>
	  <input
		type="file"
		ref={fileInputRef}
		multiple
		accept="image/*"
		class="hidden"
		onChange$={onInputChange}
	  />
	</div>
  );
});