import { useState, useCallback } from 'react';
import type { UseFileUploadReturn } from './types';

const ACCEPTED_EXTENSIONS = ['xlsx', 'docx', 'pptx', 'pdf'];
const MAX_FILE_SIZE = 50 * 1024 * 1024;

export const ERROR_MESSAGES = {
  INVALID_FORMAT: 'Format non supporté. Formats acceptés : .xlsx, .docx, .pptx, .pdf',
  FILE_TOO_LARGE: 'Fichier trop volumineux (max 50 MB)',
} as const;

export function useFileUpload(): UseFileUploadReturn {
  const [file, setFile] = useState<File | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [isDragOver, setIsDragOver] = useState(false);

  const validateFile = useCallback((file: File): string | null => {
    const ext = file.name.split('.').pop()?.toLowerCase();

    if (!ext || !ACCEPTED_EXTENSIONS.includes(ext)) {
      return ERROR_MESSAGES.INVALID_FORMAT;
    }

    if (file.size > MAX_FILE_SIZE) {
      return ERROR_MESSAGES.FILE_TOO_LARGE;
    }

    return null;
  }, []);

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragOver(false);

    const droppedFile = e.dataTransfer.files[0];
    if (droppedFile) {
      const validationError = validateFile(droppedFile);
      if (validationError) {
        setError(validationError);
        setFile(null);
      } else {
        setFile(droppedFile);
        setError(null);
      }
    }
  }, [validateFile]);

  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragOver(true);
  }, []);

  const handleDragLeave = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragOver(false);
  }, []);

  const handleFileSelect = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const selected = e.target.files?.[0];
    if (selected) {
      const validationError = validateFile(selected);
      if (validationError) {
        setError(validationError);
        setFile(null);
      } else {
        setFile(selected);
        setError(null);
      }
    }
  }, [validateFile]);

  const setMockFile = useCallback((type: 'word' | 'excel' | 'slides' | 'pdf') => {
    const mockDetails: Record<string, { name: string; mime: string; size: number }> = {
      word: { name: 'rapport_strategique_q3.docx', mime: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', size: 12.4 * 1024 * 1024 },
      excel: { name: 'bilan_consolidé_2025.xlsx', mime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', size: 4.2 * 1024 * 1024 },
      slides: { name: 'keynote_produit_wordly.pptx', mime: 'application/vnd.openxmlformats-officedocument.presentationml.presentation', size: 8.0 * 1024 * 1024 },
      pdf: { name: 'cahier_des_charges_v2.pdf', mime: 'application/pdf', size: 15.1 * 1024 * 1024 },
    };

    const details = mockDetails[type];
    if (details) {
      // Create a dummy blob representing the file size
      const dummyBlob = new Blob(['x'.repeat(100)], { type: details.mime });
      // Create a custom File object that overrides size properties
      const mockFile = new File([dummyBlob], details.name, {
        type: details.mime,
        lastModified: Date.now()
      });
      // Override the readonly size property for display purposes
      Object.defineProperty(mockFile, 'size', { value: details.size });
      
      setFile(mockFile);
      setError(null);
    }
  }, []);

  const removeFile = useCallback(() => {
    setFile(null);
    setError(null);
    setIsDragOver(false);
  }, []);

  return {
    file,
    error,
    isDragOver,
    handleDrop,
    handleDragOver,
    handleDragLeave,
    handleFileSelect,
    removeFile,
    setMockFile,
  };
}
