import { useMemo } from "react";
import { QuadViewRenderer } from "./QuadViewRenderer";
import { NiftiQuadViewRenderer } from "./NiftiQuadViewRenderer";
import { useDicomData } from "./useDicomData";
import { useNiftiData } from "./useNiftiData";
// Updated import to include Active2DView
import type { ViewOrientation, Active2DView } from "./ViewRotationControls";
import type { BoundingBox, SegmentationMask } from "./types";
import type { OrganMaskData } from "./types";
import type { Annotation, AnnotationTool } from "./types";

export type FileFormat = "dicom" | "nifti" | null;

export interface UnifiedQuadViewRendererProps {
  files: File[];
  windowWidth: number;
  windowLevel: number;
  opacity: number;
  isLoading?: boolean;
  onRotate3D?: (orientation: ViewOrientation) => void;
  active2DView?: Active2DView;
  currentOrientation?: ViewOrientation;
  // Segmentation props
  segmentationEnabled?: boolean;
  boundingBox?: BoundingBox | null;
  onBoundingBoxChange?: (box: BoundingBox | null) => void;
  currentSliceIndex?: number;
  onSliceIndexChange?: (index: number) => void;
  segmentationMask?: SegmentationMask | null;
  // Organ mask overlays
  organMasks?: OrganMaskData[];
  // Client-side annotation tools (bbox / points / pen / brush / polygon)
  annotationTool?: AnnotationTool;
  annotations?: Annotation[];
  onAnnotationsChange?: (annotations: Annotation[]) => void;
}

/**
 * Detects file format based on file extensions
 */
const detectFileFormat = (files: File[]): FileFormat => {
  if (files.length === 0) return null;
  
  // Check if any file is NIfTI
  const hasNifti = files.some(file => {
    const name = file.name.toLowerCase();
    return name.endsWith(".nii") || name.endsWith(".nii.gz");
  });
  
  if (hasNifti) {
    // If there's a mix, prioritize NIfTI if it's a single file
    if (files.length === 1) return "nifti";
    // If multiple files and one is NIfTI, still treat as NIfTI (use first NIfTI file)
    return "nifti";
  }
  
  // Check if files are DICOM
  const hasDicom = files.some(file => {
    const name = file.name.toLowerCase();
    return name.endsWith(".dcm") || name.endsWith(".dicom");
  });
  
  if (hasDicom) return "dicom";
  
  return null;
};

/**
 * Unified Quad View Renderer that automatically switches between
 * DICOM and NIfTI renderers based on uploaded file format
 */
export const UnifiedQuadViewRenderer = ({
  files,
  windowWidth,
  windowLevel,
  opacity,
  isLoading: externalLoading = false,
  onRotate3D,
  active2DView,
  currentOrientation,
  // Segmentation props
  segmentationEnabled = false,
  boundingBox,
  onBoundingBoxChange,
  currentSliceIndex = 0,
  onSliceIndexChange,
  segmentationMask,
  // Organ mask overlays
  organMasks = [],
  annotationTool = "none",
  annotations = [],
  onAnnotationsChange,
}: UnifiedQuadViewRendererProps) => {
  // Detect file format
  const fileFormat = useMemo(() => detectFileFormat(files), [files]);
  
  // Get the first NIfTI file if format is NIfTI
  // Use a more specific key to ensure changes are detected
  const niftiFile = useMemo(() => {
    if (fileFormat === "nifti") {
      const niftiFile = files.find(file => {
        const name = file.name.toLowerCase();
        return name.endsWith(".nii") || name.endsWith(".nii.gz");
      });
      return niftiFile || null;
    }
    return null;
  }, [files, fileFormat]);

  // Get DICOM files if format is DICOM - filter out any NIfTI files that might be mixed in
  const dicomFileObjects = useMemo(() => {
    if (fileFormat === "dicom") {
      return files.filter(file => {
        const name = file.name.toLowerCase();
        return name.endsWith(".dcm") || name.endsWith(".dicom");
      });
    }
    return [];
  }, [files, fileFormat]);

  // Use appropriate hooks based on file format
  const { dicomData, isLoading: isDicomLoading } = useDicomData(dicomFileObjects);
  const { niftiData, isLoading: isNiftiLoading, error: niftiError } = useNiftiData(niftiFile);
  
  const isLoading = externalLoading || (fileFormat === "dicom" ? isDicomLoading : isNiftiLoading);

  // Render appropriate component based on file format
  if (fileFormat === "nifti") {
    return (
      <>
        <NiftiQuadViewRenderer
          niftiData={niftiData}
          windowWidth={windowWidth}
          windowLevel={windowLevel}
          opacity={opacity}
          isLoading={isLoading}
          onRotate3D={onRotate3D}
          active2DView={active2DView}
          currentOrientation={currentOrientation}
          segmentationEnabled={segmentationEnabled}
          boundingBox={boundingBox}
          onBoundingBoxChange={onBoundingBoxChange}
          currentSliceIndex={currentSliceIndex}
          onSliceIndexChange={onSliceIndexChange}
          segmentationMask={segmentationMask}
          organMasks={organMasks}
          annotationTool={annotationTool}
          annotations={annotations}
          onAnnotationsChange={onAnnotationsChange}
        />
        {niftiError && (
          <div className="absolute inset-0 flex items-center justify-center z-30 bg-background/90 backdrop-blur-sm">
            <div className="text-center p-8 bg-destructive/10 border border-destructive rounded-lg">
              <p className="text-destructive font-semibold">Error loading NIfTI file</p>
              <p className="text-sm text-muted-foreground mt-2">{niftiError}</p>
            </div>
          </div>
        )}
      </>
    );
  }

  if (fileFormat === "dicom") {
    return (
      <QuadViewRenderer
        dicomData={dicomData}
        windowWidth={windowWidth}
        windowLevel={windowLevel}
        opacity={opacity}
        isLoading={isLoading}
        onRotate3D={onRotate3D}
        active2DView={active2DView}
        currentOrientation={currentOrientation} // Pass it
      />
    );
  }

  // No files or unknown format
  return (
    <div className="absolute inset-0 flex items-center justify-center z-20">
      <div className="text-center p-8">
        <div className="text-6xl mb-4 opacity-30">🩻</div>
        <p className="text-muted-foreground">Upload DICOM or NIfTI files to view</p>
        <p className="text-xs text-muted-foreground mt-2">
          Supported formats: .dcm, .dicom, .nii, .nii.gz
        </p>
      </div>
    </div>
  );
};