"use client";
import { FileUploader } from "./fileUpload";
import { useState, useEffect, useRef } from "react"; // Added useRef import
import { toast } from "sonner";

export interface FileInfo {
  fileName: string;
  contentType: string;
  originalname: string;
}

export interface Name {
  am: string;
  en: string;
}

export interface UploadRequestBody {
  fileInfo: FileInfo;
  name: Name;
  recordContentId: string;
}

export interface UploadResponse {
  uploadUrl: string;
  attachmentId: string;
}

export function ReusableFileUploader({
  setFiles,
  files,
  canUploadIndividual = false,
  isLoading,
  uploadIndividualFun,
}: {
  setFiles?: (files: File[]) => void;
  files: File[];
  isLoading: boolean;
  canUploadIndividual?: boolean;
  uploadIndividualFun?: () => void;
}) {
  const [error, setError] = useState<string | null>(null);
  const lastFiles = useRef<File[]>([]); // Now properly defined
  useEffect(() => {
    lastFiles.current = files;
  }, [files]);

  const handleFileChange = (newFiles: File[]) => {
    if (setFiles) {
      // Only update if files actually changed
      if (
        newFiles.length !== lastFiles.current.length ||
        newFiles.some((f, i) => f !== lastFiles.current[i])
      ) {
        setFiles(newFiles);
        setError(null);
      }
    }
  };

  return (
    <div className="flex flex-col gap-6">
      <FileUploader
        maxFileCount={30}
        maxSize={200 * 1024 * 1024}
        value={files}
        onValueChange={handleFileChange}
        disabled={isLoading}
        canUploadIndividual={canUploadIndividual}
        uploadIndividualFun={uploadIndividualFun}
      />
      {isLoading && <p className="text-muted-foreground">Uploading...</p>}
      {error && <p className="text-red-500 dark:text-red-400">{error}</p>}
    </div>
  );
}
