import { useState, useEffect, useRef } from "react";
import type { NiftiData } from "./types";
import { parseNiftiBuffer } from "./niftiLoader";

export function useNiftiData(file: File | null) {
  const [niftiData, setNiftiData] = useState<NiftiData | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const lastFileRef = useRef<string>("");

  useEffect(() => {
    if (!file) {
      setNiftiData(null);
      lastFileRef.current = "";
      return;
    }

    // Create a unique identifier for the file to detect changes
    // Use name, size, and lastModified to ensure we detect different files
    const fileKey = `${file.name}-${file.size}-${file.lastModified}`;
    
    // Skip if we already loaded this exact file
    if (fileKey === lastFileRef.current && niftiData) {
      return;
    }

    lastFileRef.current = fileKey;

    const loadNifti = async () => {
      setIsLoading(true);
      setError(null);

      try {
        const arrayBuffer = await file.arrayBuffer();
        setNiftiData(parseNiftiBuffer(arrayBuffer));
      } catch (err) {
        console.error("Error loading NIfTI:", err);
        setError(err instanceof Error ? err.message : "Failed to load NIfTI file");
        setNiftiData(null);
      } finally {
        setIsLoading(false);
      }
    };

    loadNifti();
  }, [file, niftiData]);

  return { niftiData, isLoading, error };
}