"use client";
import { createClient } from "@/utils/supabase/client";
import { CloudUpload } from "lucide-react";

export default async function UploadZone() {
  const supabase = await createClient();

  const {
    data: { user },
  } = await supabase.auth.getUser();

  const onUpload = async (file: File) => {
    const uuid = crypto.randomUUID();

    const { data: fileData, error: fileError } = await supabase.storage
      .from("documents")
      .upload(`public/${uuid}.pdf`, file);

    if (fileError) {
      console.error(fileError);
      return;
    }

    console.log("File uploaded successfully:", fileData);

    const { data, error } = await supabase.from("documents").insert({
      id: uuid,
      file_name: file.name,
      owner: user!.id,
      raw_file: fileData.id,
    });

    if (error) {
      console.error(error);
      return;
    }

    console.log("Document inserted successfully:", data);

    // process file at /dashboard/upload/process
    const formData = new FormData();
    formData.append("file", file);
    formData.append("fileName", file.name);
    formData.append("id", uuid);
    const response = await fetch("/dashboard/upload/process", {
      method: "POST",
      body: formData,
    });
    const result = await response.json();
    console.log("File processed successfully:", result);
  };

  return (
    <div className="flex flex-1 flex-col gap-4 px-4 py-10">
      <div className="flex items-center justify-center w-full">
        <label
          htmlFor="dropzone-file"
          className="flex flex-col items-center justify-center w-full h-64 border-2 border-muted border-dashed rounded-lg cursor-pointer bg-muted/50"
        >
          <div className="flex flex-col items-center justify-center pt-5 pb-5">
            <CloudUpload className="w-10 h-10 mb-4 text-slate-400" />
            <p className="mb-2 text-sm text-slate-400">
              <span className="font-semibold">Click to upload</span> or drag and
              drop
            </p>
          </div>
          <input
            id="dropzone-file"
            type="file"
            className="hidden"
            accept="application/pdf"
            onChange={(e) => {
              const file = e.target.files?.[0];
              if (file) {
                onUpload(file);
              }
            }}
          />
        </label>
      </div>
    </div>
  );
}
