"use client";

import { useState } from "react";

// Define the structure of an uploaded file
export interface UploadedFile {
  name: string;
  size: number;
  type: string;
  buffer: ArrayBuffer;
  preview: string;
}

export interface UploadProgress {
  [key: string]: number; // ✅ Use string index for compatibility
}

export function useUploadFile() {
  const [uploadedFiles, setUploadedFiles] = useState<UploadedFile[]>([]);
  const [progresses, setProgresses] = useState<UploadProgress>({});
  const [isUploading, setIsUploading] = useState<boolean>(false);

  // Accepts File[] instead of FileList
  const onUpload = async (files: File[]) => {
    setIsUploading(true);

    const filePromises: Promise<UploadedFile>[] = files.map((file, index) => {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        const previewReader = new FileReader();
        reader.onload = (event) => {
          if (event.target?.result instanceof ArrayBuffer) {
            previewReader.readAsDataURL(file); // Convert for preview

            previewReader.onload = () => {
              resolve({
                name: file.name,
                size: file.size,
                type: file.type,
                buffer: event.target!.result as ArrayBuffer,
                preview: previewReader.result as string, // Store preview
              });
            };
          } else {
            reject(new Error("Failed to read file as ArrayBuffer."));
          }
        };

        reader.onerror = () => reject(new Error("File reading error"));
        reader.readAsArrayBuffer(file);

        // Convert index to string for progresses
        const fileIndex = index.toString();
        setProgresses((prev) => ({ ...prev, [fileIndex]: 0 }));

        setTimeout(() => {
          setProgresses((prev) => ({ ...prev, [fileIndex]: 100 }));
        }, 1000);
      });
    });

    try {
      const fileBuffers = await Promise.all(filePromises);
      setUploadedFiles((prev) => [...prev, ...fileBuffers]);
    } catch (error) {
    } finally {
      setIsUploading(false);
    }
  };

  return {
    onUpload,
    progresses,
    uploadedFiles,
    isUploading,
  };
}
