import { useState, useMemo, useCallback } from 'react';

export interface FleetFileNode {
  id: string;
  name: string;
  type: 'folder' | 'file';
  fileType?: 'pdf' | 'image' | 'word' | 'excel' | 'other';
  documentType?: string;
  vehicleId?: string;
  category?: string;
  status?: string;
  size?: string;
  addedBy?: string;
  addedDate?: Date;
  lastModified?: Date;
  isFavorite?: boolean;
  children?: FleetFileNode[];
  path?: string;
}

export type ViewMode = 'grid' | 'list';
export type SortBy = 'name' | 'date' | 'type' | 'size' | 'user';

interface UseFleetFileManagerProps {
  initialData: FleetFileNode[];
}

export function useFleetFileManager({ initialData }: UseFleetFileManagerProps) {
  const [fileStructure, setFileStructure] = useState<FleetFileNode[]>(initialData);
  const [currentPath, setCurrentPath] = useState<string[]>(['Accueil']);
  const [currentFolder, setCurrentFolder] = useState<FleetFileNode[]>(initialData);
  const [viewMode, setViewMode] = useState<ViewMode>('grid');
  const [searchQuery, setSearchQuery] = useState('');
  const [filterType, setFilterType] = useState('Tous les types');
  const [sortBy, setSortBy] = useState<SortBy>('name');
  const [selectedItems, setSelectedItems] = useState<string[]>([]);
  // Removed showFavoritesOnly since favorites are not needed

  // Navigate to folder
  const navigateToFolder = useCallback((folder: FleetFileNode) => {
    if (folder.type === 'folder' && folder.children) {
      setCurrentPath(prev => [...prev, folder.name]);
      setCurrentFolder(folder.children);
      setSelectedItems([]);
    }
  }, []);

  // Navigate via breadcrumb
  const navigateToBreadcrumb = useCallback((index: number) => {
    const newPath = currentPath.slice(0, index + 1);
    setCurrentPath(newPath);
    
    if (index === 0) {
      setCurrentFolder(fileStructure);
    } else {
      // In a real app, you'd navigate to the correct folder based on path
      setCurrentFolder(fileStructure);
    }
    setSelectedItems([]);
  }, [currentPath, fileStructure]);

  // Removed toggleFavorite function since favorites are not needed

  // Add new folder
  const addFolder = useCallback((folderName: string, parentPath?: string[]) => {
    const newFolder: FleetFileNode = {
      id: `folder-${Date.now()}`,
      name: folderName,
      type: 'folder',
      addedBy: 'Utilisateur actuel',
      addedDate: new Date(),
      lastModified: new Date(),
      children: [],
      isFavorite: false,
    };

    // Add to current folder
    setCurrentFolder(prev => [...prev, newFolder]);
    
    // Also update the file structure if we're at root
    if (currentPath.length === 1) {
      setFileStructure(prev => [...prev, newFolder]);
    }
  }, [currentPath]);

  // Upload file
  const uploadFile = useCallback((file: File, metadata: Partial<FleetFileNode>) => {
    const newFile: FleetFileNode = {
      id: `file-${Date.now()}`,
      name: file.name,
      type: 'file',
      fileType: getFileType(file.name),
      size: formatFileSize(file.size),
      addedBy: 'Utilisateur actuel',
      addedDate: new Date(),
      lastModified: new Date(),
      isFavorite: false,
      ...metadata,
    };

    // Add to current folder
    setCurrentFolder(prev => [...prev, newFile]);
    
    // Also update the file structure if we're at root
    if (currentPath.length === 1) {
      setFileStructure(prev => [...prev, newFile]);
    }
  }, [currentPath]);

  // Delete items
  const deleteItems = useCallback((itemIds: string[]) => {
    setCurrentFolder(prev => prev.filter(item => !itemIds.includes(item.id)));
    setSelectedItems([]);
  }, []);

  // Removed copyItems function since copying is not needed

  // Rename item
  const renameItem = useCallback((itemId: string, newName: string) => {
    const updateNodeName = (nodes: FleetFileNode[]): FleetFileNode[] => {
      return nodes.map(node => {
        if (node.id === itemId) {
          return { 
            ...node, 
            name: newName,
            lastModified: new Date(),
          };
        }
        if (node.children) {
          return { ...node, children: updateNodeName(node.children) };
        }
        return node;
      });
    };

    setFileStructure(updateNodeName);
    setCurrentFolder(prev => updateNodeName(prev));
  }, []);

  // Selection management
  const selectItem = useCallback((itemId: string) => {
    setSelectedItems(prev => 
      prev.includes(itemId) 
        ? prev.filter(id => id !== itemId)
        : [...prev, itemId]
    );
  }, []);

  const selectAll = useCallback(() => {
    const allIds = currentFolder.map(item => item.id);
    if (selectedItems.length === allIds.length) {
      setSelectedItems([]);
    } else {
      setSelectedItems(allIds);
    }
  }, [currentFolder, selectedItems]);

  // Filtered and sorted items
  const filteredAndSortedItems = useMemo(() => {
    let items = [...currentFolder];

    // Apply search filter
    if (searchQuery) {
      items = items.filter(item => 
        item.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
        item.vehicleId?.toLowerCase().includes(searchQuery.toLowerCase()) ||
        item.addedBy?.toLowerCase().includes(searchQuery.toLowerCase())
      );
    }

    // Apply type filter
    if (filterType !== 'Tous les types') {
      items = items.filter(item => 
        item.type === 'folder' || item.documentType === filterType
      );
    }

    // Apply favorites filter
    // Removed showFavoritesOnly filter

    // Apply sorting
    items.sort((a, b) => {
      switch (sortBy) {
        case 'name':
          return a.name.localeCompare(b.name);
        case 'date':
          return (b.addedDate?.getTime() || 0) - (a.addedDate?.getTime() || 0);
        case 'type':
          if (a.type !== b.type) return a.type === 'folder' ? -1 : 1;
          return (a.documentType || '').localeCompare(b.documentType || '');
        case 'user':
          return (a.addedBy || '').localeCompare(b.addedBy || '');
        default:
          return 0;
      }
    });

    return items;
  }, [currentFolder, searchQuery, filterType, sortBy]);

  // Export data for Excel
  const getExportData = useCallback(() => {
    return currentFolder.map(item => ({
      Nom: item.name,
      Type: item.type === 'folder' ? 'Dossier' : 'Fichier',
      'Type de document': item.documentType || '-',
      Véhicule: item.vehicleId || '-',
      Catégorie: item.category || '-',
      Statut: item.status || '-',
      Taille: item.size || '-',
      'Ajouté par': item.addedBy || '-',
      'Date d&apos;ajout': item.addedDate?.toLocaleDateString() || '-',
      'Dernière modification': item.lastModified?.toLocaleDateString() || '-',
    }));
  }, [currentFolder]);

  return {
    // State
    fileStructure,
    currentPath,
    currentFolder,
    viewMode,
    searchQuery,
    filterType,
    sortBy,
    selectedItems,
    // Removed showFavoritesOnly from return
    filteredAndSortedItems,

    // Actions
    setViewMode,
    setSearchQuery,
    setFilterType,
    setSortBy,
    // Removed setShowFavoritesOnly from return
    navigateToFolder,
    navigateToBreadcrumb,
    addFolder,
    uploadFile,
    deleteItems,
    renameItem,
    selectItem,
    selectAll,
    getExportData,
  };
}

// Helper functions
function getFileType(fileName: string): 'pdf' | 'image' | 'word' | 'excel' | 'other' {
  const ext = fileName.split('.').pop()?.toLowerCase();
  switch (ext) {
    case 'pdf':
      return 'pdf';
    case 'jpg':
    case 'jpeg':
    case 'png':
    case 'gif':
    case 'svg':
      return 'image';
    case 'doc':
    case 'docx':
      return 'word';
    case 'xls':
    case 'xlsx':
      return 'excel';
    default:
      return 'other';
  }
}

function formatFileSize(bytes: number): string {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
} 