'use client';

import {
  Box,
  Stack,
  Button,
  MenuItem,
  IconButton,
  Typography,
  Breadcrumbs,
  Link,
  Card,
  CardContent,
  Grid,
  List,
  ListItem,
  ListItemIcon,
  ListItemText,
  ListItemSecondaryAction,
  Checkbox,
  Menu,
  Select,
  FormControl,
  InputAdornment,
  ToggleButtonGroup,
  ToggleButton,
  InputBase,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogContentText,
  DialogActions,
} from '@mui/material';
import { useState, useCallback } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
  faFolder,
  faFile,
  faPlus,
  faSearch,
  faFilter,
  faFileExcel,
  faGrip,
  faList,
  faEllipsisV,
  faHome,
  faChevronRight,
  faDownload,
  faEdit,
  faTrash,
  faFileImage,
  faFilePdf,
  faFileWord,
  faSort,
  faPen
} from '@fortawesome/free-solid-svg-icons';
import { StyledTextField } from '@/shared/theme/css';
import FontAwesome from '@/shared/components/fontawesome';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { formatDate } from '@/utils/format-time';
import { FleetDocumentStatusChip } from '../styles';
import { FleetFileNode } from '../hooks/use-fleet-file-manager';
import { useFleetDocuments } from '../hooks/use-fleet-documents';
import AddFolderDialog from '../components/add-folder-dialog';
import UploadFileDialog from '../components/upload-file-dialog';
import RenameDialog from '../components/rename-dialog';
import SimpleDocumentEditor from '../components/simple-document-editor';
import axiosInstance from '@/utils/axios';
import { fleetDocumentEndpoints } from '@/shared/api/endpoints/fleet/fleet-documents';

const DOCUMENT_TYPES = [
  'Tous les types',
  'assurance',
  'carte_grise',
  'controle_technique',
  'contrat_location',
  'revision',
  'permis_conduire',
  'autre'
];

export default function FleetFileManager() {
  // Récupérer l'UUID de l'utilisateur connecté
  const ownerUuid = localStorage.getItem('userUuid') || '';

  const {
    currentPath,
    viewMode,
    searchQuery,
    filterType,
    sortBy,
    selectedItems,
    filteredAndSortedItems,
    loading,
    error,
    storageQuota,
    setViewMode,
    setSearchQuery,
    setFilterType,
    setSortBy,
    navigateToFolder,
    navigateToBreadcrumb,
    addFolder,
    uploadFile,
    deleteItems,
    renameItem,
    downloadDocument,
    downloadFolder,
    selectItem,
    selectAll,
    getExportData,
    refreshData,
  } = useFleetDocuments(ownerUuid);

  const [contextMenuAnchor, setContextMenuAnchor] = useState<null | HTMLElement>(null);
  const [contextMenuItem, setContextMenuItem] = useState<FleetFileNode | null>(null);
  const [addFolderOpen, setAddFolderOpen] = useState(false);
  const [uploadFileOpen, setUploadFileOpen] = useState(false);
  const [renameDialogOpen, setRenameDialogOpen] = useState(false);
  const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
  const [itemsToDelete, setItemsToDelete] = useState<string[]>([]);
  const [editDialogOpen, setEditDialogOpen] = useState(false);
  const [editingDocument, setEditingDocument] = useState<any>(null);

  const getFileIcon = useCallback((file: FleetFileNode) => {
    if (file.type === 'folder') return faFolder;
    switch (file.fileType) {
      case 'pdf': return faFilePdf;
      case 'image': return faFileImage;
      case 'word': return faFileWord;
      case 'excel': return faFileExcel;
      default: return faFile;
    }
  }, []);

  const handleContextMenu = useCallback((event: React.MouseEvent, item: FleetFileNode) => {
    event.preventDefault();
    setContextMenuAnchor(event.currentTarget as HTMLElement);
    setContextMenuItem(item);
  }, []);

  const handleExportExcel = useCallback(() => {
    const data = getExportData();
    
    if (data.length === 0) {
      alert('Aucune donnée à exporter');
      return;
    }

    // Créer le CSV avec BOM UTF-8
    const BOM = '\uFEFF';
    const headers = Object.keys(data[0]).join(',');
    const rows = data.map(row => 
      Object.values(row).map(value => 
        JSON.stringify(value ?? '')
      ).join(',')
    );
    
    const csvContent = BOM + [headers, ...rows].join('\n');
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = window.URL.createObjectURL(blob);
    
    const link = document.createElement('a');
    link.href = url;
    link.download = `fleet-documents-${new Date().toISOString().split('T')[0]}.csv`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  }, [getExportData]);

  const handleFileUpload = useCallback((files: File[], metadata: any) => {
    files.forEach(file => {
      uploadFile(file, metadata);
    });
  }, [uploadFile]);

  const handleRename = useCallback((newName: string) => {
    if (contextMenuItem) {
      renameItem(contextMenuItem.id, newName);
    }
  }, [contextMenuItem, renameItem]);

  const handleDownload = useCallback(async (item: FleetFileNode) => {
    try {
      if (item.type === 'file') {
        await downloadDocument(item);
      } else {
        await downloadFolder(item);
      }
    } catch (error) {
      console.error('Erreur lors du téléchargement:', error);
    }
  }, [downloadDocument, downloadFolder]);

  const handleDeleteClick = useCallback((itemIds: string[]) => {
    setItemsToDelete(itemIds);
    setDeleteConfirmOpen(true);
  }, []);

  const handleDeleteConfirm = useCallback(async () => {
    try {
      await deleteItems(itemsToDelete);
      setDeleteConfirmOpen(false);
      setItemsToDelete([]);
    } catch (error) {
      console.error('Erreur lors de la suppression:', error);
    }
  }, [deleteItems, itemsToDelete]);

  const handleDeleteCancel = useCallback(() => {
    setDeleteConfirmOpen(false);
    setItemsToDelete([]);
  }, []);

  const handleEdit = useCallback(async (item: FleetFileNode) => {
    if (item.type === 'folder') {
      return;
    }

    // Only allow editing Word and Excel files
    if (item.fileType !== 'word' && item.fileType !== 'excel') {
      alert('Seuls les fichiers Word et Excel peuvent être modifiés');
      return;
    }

    try {
      // Use the existing download endpoint to get the document URL
      // This generates a presigned URL that can be used for downloading
      const downloadUrl = `${fleetDocumentEndpoints.download}?documentId=${item.id}&ownerUuid=${ownerUuid}`;
      
      // Open document editor dialog with download URL
      setEditingDocument({ ...item, downloadUrl });
      setEditDialogOpen(true);
    } catch (error) {
      alert('Erreur lors de l\'ouverture du document pour modification');
    }
  }, [ownerUuid]);

  // Handle document save from simple editor
  const handleDocumentSave = useCallback(async (content: string, metadata: any) => {
    if (!editingDocument) return;

    try {
      // Créer un fichier HTML à partir du contenu édité
      const blob = new Blob([content], { type: 'text/html' });
      const file = new File(
        [blob],
        `${editingDocument.name.split('.')[0]}_edited.html`,
        { type: 'text/html' }
      );

      // Upload comme nouvelle version  
      await uploadFile(file, {
        documentType: editingDocument.documentType || 'autre',
      });

      // Refresh the file list
      await refreshData();
    } catch (error) {
      console.error('Erreur lors de la sauvegarde:', error);
      throw error;
    }
  }, [editingDocument, uploadFile, refreshData]);

  // Check if an item can be edited (only Word and Excel files)
  const canEditItem = useCallback((item: FleetFileNode | null): boolean => {
    if (!item || item.type === 'folder') return false;
    return item.fileType === 'word' || item.fileType === 'excel';
  }, []);

  const renderGridView = () => (
    <Grid container spacing={3}>
      {filteredAndSortedItems.map((item) => (
        <Grid item xs={12} sm={6} md={4} lg={3} key={item.id}>
          <Card
            sx={{
              cursor: 'pointer',
              height: 280,
              position: 'relative',
              border: selectedItems.includes(item.id) ? 2 : 1,
              borderColor: selectedItems.includes(item.id) ? 'primary.main' : 'divider',
              '&:hover': {
                boxShadow: 4,
                transform: 'translateY(-2px)',
                transition: 'all 0.2s ease-in-out'
              },
              borderRadius: 2,
              overflow: 'hidden',
            }}
            onClick={() => item.type === 'folder' ? navigateToFolder(item) : selectItem(item.id)}
            onContextMenu={(e) => handleContextMenu(e, item)}
          >
            <CardContent sx={{ p: 2.5, height: '100%', display: 'flex', flexDirection: 'column' }}>
              {/* Header with checkbox only */}
              <Box sx={{
                position: 'absolute',
                top: 12,
                left: 12,
                right: 12,
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center'
              }}>
                <Checkbox
                  checked={selectedItems.includes(item.id)}
                  onChange={() => selectItem(item.id)}
                  onClick={(e) => e.stopPropagation()}
                  size="small"
                  sx={{ p: 0.5 }}
                />
                {/* Removed favorite star */}
              </Box>

              {/* File/Folder Icon */}
              <Box sx={{
                textAlign: 'center',
                mt: 4,
                mb: 2,
                flex: '0 0 auto'
              }}>
                <FontAwesome
                  icon={getFileIcon(item)}
                  width={56}
                  style={{
                    color: item.type === 'folder' ? '#42A5F5' : '#666'
                  }}
                />
              </Box>

              {/* File Name */}
              <Box sx={{ mb: 2, textAlign: 'center' }}>
                <Typography
                  variant="body1"
                  sx={{
                    fontWeight: 600,
                    lineHeight: 1.3,
                    wordBreak: 'break-word',
                    fontSize: '0.95rem'
                  }}
                >
                  {item.name}
                </Typography>
              </Box>

              {/* Document Information */}
              <Box sx={{ mt: 'auto', pt: 1 }}>
                <Stack spacing={1}>
                  {/* Type de document */}
                  <ConditionalComponent isValid={!!item.documentType}>
                    <Box sx={{ textAlign: 'center' }}>
                      <FleetDocumentStatusChip
                        type={item.documentType || ''}
                        label={item.documentType ?
                          (item.documentType.replace('_', ' ').charAt(0).toUpperCase() + item.documentType.replace('_', ' ').slice(1))
                          : ''
                        }
                        sx={{
                          height: 24,
                          fontSize: '0.75rem',
                          minWidth: '80px'
                        }}
                      />
                    </Box>
                  </ConditionalComponent>

                  {/* Véhicule associé */}
                  <ConditionalComponent isValid={!!item.vehicleId}>
                    <Typography
                      variant="caption"
                      color="primary.main"
                      sx={{
                        textAlign: 'center',
                        fontWeight: 500,
                        fontSize: '0.8rem'
                      }}
                    >
                      🚗 {item.vehicleId}
                    </Typography>
                  </ConditionalComponent>

                  {/* Date d'ajout */}
                  <Typography
                    variant="caption"
                    color="text.secondary"
                    sx={{
                      textAlign: 'center',
                      fontSize: '0.75rem'
                    }}
                  >
                    📅 {formatDate(item.addedDate)}
                  </Typography>

                  {/* Utilisateur et taille */}
                  <Typography
                    variant="caption"
                    color="text.secondary"
                    sx={{
                      textAlign: 'center',
                      fontSize: '0.75rem'
                    }}
                  >
                    👤 {item.addedBy} {item.size && `• ${item.size}`}
                  </Typography>
                </Stack>
              </Box>
            </CardContent>
          </Card>
        </Grid>
      ))}
    </Grid>
  );

  const renderListView = () => (
    <List sx={{ px: 1 }}>
      {filteredAndSortedItems.map((item) => (
        <ListItem
          key={item.id}
          sx={{
            border: 1,
            borderColor: 'divider',
            borderRadius: 2,
            mb: 2,
            bgcolor: selectedItems.includes(item.id) ? 'action.selected' : 'background.paper',
            '&:hover': {
              bgcolor: 'action.hover',
              transform: 'translateX(4px)',
              transition: 'all 0.2s ease-in-out'
            },
            cursor: 'pointer',
            minHeight: 80,
            alignItems: 'flex-start',
            py: 2,
            px: 2.5,
          }}
          onClick={() => item.type === 'folder' ? navigateToFolder(item) : selectItem(item.id)}
          onContextMenu={(e) => handleContextMenu(e, item)}
        >
          <Checkbox
            checked={selectedItems.includes(item.id)}
            onChange={() => selectItem(item.id)}
            onClick={(e) => e.stopPropagation()}
            sx={{ mt: 0.5, mr: 2 }}
          />
          <ListItemIcon sx={{ minWidth: 60, mt: 0.5 }}>
            <FontAwesome
              icon={getFileIcon(item)}
              width={32}
              style={{ color: item.type === 'folder' ? '#42A5F5' : '#666' }}
            />
          </ListItemIcon>
          <ListItemText
            sx={{ flex: 1 }}
            primary={
              <Stack direction="row" alignItems="center" spacing={2} sx={{ mb: 1 }}>
                <Typography variant="h6" sx={{ fontWeight: 600, fontSize: '1.1rem' }}>
                  {item.name}
                </Typography>
                {/* Removed favorite star */}
                <ConditionalComponent isValid={!!item.documentType}>
                  <FleetDocumentStatusChip
                    type={item.documentType || ''}
                    label={item.documentType ?
                      (item.documentType.replace('_', ' ').charAt(0).toUpperCase() + item.documentType.replace('_', ' ').slice(1))
                      : ''
                    }
                    sx={{ height: 28, fontSize: '0.8rem' }}
                  />
                </ConditionalComponent>
              </Stack>
            }
            secondary={
              <Stack spacing={1}>
                {/* Première ligne : Véhicule et Date */}
                <Stack direction="row" spacing={4} sx={{ alignItems: 'center' }}>
                  <ConditionalComponent isValid={!!item.vehicleId}>
                    <Stack direction="row" alignItems="center" spacing={0.5}>
                      <Typography variant="body2" color="text.secondary" sx={{ fontSize: '0.75rem' }}>
                        🚗 Véhicule:
                      </Typography>
                      <Typography variant="body2" color="primary.main" sx={{ fontWeight: 500 }}>
                        {item.vehicleId}
                      </Typography>
                    </Stack>
                  </ConditionalComponent>

                  <Stack direction="row" alignItems="center" spacing={0.5}>
                    <Typography variant="body2" color="text.secondary" sx={{ fontSize: '0.75rem' }}>
                      📅 Date d&apos;ajout:
                    </Typography>
                    <Typography variant="body2" color="text.secondary">
                      {formatDate(item.addedDate)}
                    </Typography>
                  </Stack>
                </Stack>

                {/* Deuxième ligne : Utilisateur et Taille */}
                <Stack direction="row" spacing={4} sx={{ alignItems: 'center' }}>
                  <Stack direction="row" alignItems="center" spacing={0.5}>
                    <Typography variant="body2" color="text.secondary" sx={{ fontSize: '0.75rem' }}>
                      👤 Ajouté par:
                    </Typography>
                    <Typography variant="body2" color="text.secondary">
                      {item.addedBy}
                    </Typography>
                  </Stack>

                  <ConditionalComponent isValid={!!item.size}>
                    <Stack direction="row" alignItems="center" spacing={0.5}>
                      <Typography variant="body2" color="text.secondary" sx={{ fontSize: '0.75rem' }}>
                        📁 Taille:
                      </Typography>
                      <Typography variant="body2" color="text.secondary">
                        {item.size}
                      </Typography>
                    </Stack>
                  </ConditionalComponent>

                  <Stack direction="row" alignItems="center" spacing={0.5}>
                    <Typography variant="body2" color="text.secondary" sx={{ fontSize: '0.75rem' }}>
                      🕒 Modifié:
                    </Typography>
                    <Typography variant="body2" color="text.secondary">
                      {formatDate(item.lastModified)}
                    </Typography>
                  </Stack>
                </Stack>
              </Stack>
            }
          />
          <ListItemSecondaryAction sx={{ right: 16, top: '50%', transform: 'translateY(-50%)' }}>
            <IconButton
              size="large"
              onClick={(e) => handleContextMenu(e, item)}
              sx={{
                bgcolor: 'action.hover',
                '&:hover': { bgcolor: 'action.selected' }
              }}
            >
              <FontAwesome icon={faEllipsisV} width={16} />
            </IconButton>
          </ListItemSecondaryAction>
        </ListItem>
      ))}
    </List>
  );

  return (
    <Box sx={{ height: '100vh', display: 'flex', flexDirection: 'column', p: 3, bgcolor: '#fafafa' }}>
      {/* Error Display */}
      {error && (
        <Box sx={{ mb: 2, p: 2, bgcolor: 'error.lighter', borderRadius: 2, color: 'error.main' }}>
          <Typography variant="body2">
            ⚠️ {error}
          </Typography>
        </Box>
      )}

      {/* Storage Quota Display */}
      {storageQuota && (
        <Box sx={{ mb: 2, p: 2, bgcolor: 'info.lighter', borderRadius: 2 }}>
          <Typography variant="body2" color="info.main">
            📁 Stockage: {storageQuota.usedStorageFormatted} / {storageQuota.storageQuotaFormatted} utilisés
          </Typography>
        </Box>
      )}

      {/* Breadcrumb Navigation */}
      <Box sx={{ mb: 3, p: 2, bgcolor: 'white', borderRadius: 2, boxShadow: 1 }}>
        <Breadcrumbs separator={<FontAwesome icon={faChevronRight} width={12} />}>
          {currentPath.map((path, index) => (
            <Link
              key={index}
              color={index === currentPath.length - 1 ? 'text.primary' : 'inherit'}
              href="#"
              onClick={(e) => {
                e.preventDefault();
                navigateToBreadcrumb(index);
              }}
              sx={{
                display: 'flex',
                alignItems: 'center',
                gap: 0.5,
                textDecoration: 'none',
                fontSize: '1rem',
                fontWeight: index === currentPath.length - 1 ? 600 : 400,
                '&:hover': { textDecoration: 'underline' }
              }}
            >
              <ConditionalComponent isValid={index === 0}>
                <FontAwesome icon={faHome} width={16} />
              </ConditionalComponent>
              {path}
            </Link>
          ))}
        </Breadcrumbs>
      </Box>

      {/* Action Bar */}
      <Box sx={{ mb: 4, p: 3, bgcolor: 'white', borderRadius: 2, boxShadow: 1 }}>
        <Stack direction="row" spacing={3} alignItems="center" flexWrap="wrap">
          {/* Primary Actions */}
          <Stack direction="row" spacing={2}>
            <Button
              startIcon={<FontAwesome icon={faPlus} width={16} />}
              variant="contained"
              size="medium"
              onClick={() => setAddFolderOpen(true)}
              sx={{
                minHeight: 44,
                px: 3,
                borderRadius: 2,
                textTransform: 'none',
                fontWeight: 600
              }}
            >
              + Dossier
            </Button>
            <Button
              startIcon={<FontAwesome icon={faPlus} width={16} />}
              variant="contained"
              size="medium"
              onClick={() => setUploadFileOpen(true)}
              sx={{
                minHeight: 44,
                px: 3,
                borderRadius: 2,
                textTransform: 'none',
                fontWeight: 600
              }}
            >
              + Fichier
            </Button>
          </Stack>

          {/* Search */}
          {/* Search */}
          <InputBase
            placeholder="Rechercher fichiers et dossiers"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            sx={{
              display: 'flex',
              alignItems: 'center',
              width: 300,
              border: '1px solid #6C63FF',
              borderRadius: 2,
              padding: '8px 16px',
              '& .MuiInputBase-input': {
                fontSize: '14px',
                paddingLeft: 0
              },
              '&:hover': {
                borderColor: '#6C63FF',
              },
              '&.Mui-focused': {
                borderColor: '#6C63FF',
              }
            }}
            startAdornment={
              <InputAdornment position="start">
                <FontAwesomeIcon icon={faSearch} style={{ color: '#6C63FF' }} />
              </InputAdornment>
            }
          />
          {/* Filter by Type */}
          <FormControl size="medium" sx={{ minWidth: 180 }}>
            <Select
              value={filterType}
              onChange={(e) => setFilterType(e.target.value)}
              startAdornment={
                <InputAdornment position="start">
                  <FontAwesome icon={faFilter} width={16} />
                </InputAdornment>
              }
              sx={{
                borderRadius: 2,
                minHeight: 44
              }}
            >
              {DOCUMENT_TYPES.map((type) => (
                <MenuItem key={type} value={type}>
                  {type}
                </MenuItem>
              ))}
            </Select>
          </FormControl>

          {/* Sort */}
          <FormControl size="medium" sx={{ minWidth: 140 }}>
            <Select
              value={sortBy}
              onChange={(e) => setSortBy(e.target.value as any)}
              startAdornment={
                <InputAdornment position="start">
                  <FontAwesome icon={faSort} width={16} />
                </InputAdornment>
              }
              sx={{
                borderRadius: 2,
                minHeight: 44
              }}
            >
              <MenuItem value="name">Nom</MenuItem>
              <MenuItem value="date">Date</MenuItem>
              <MenuItem value="type">Type</MenuItem>
              <MenuItem value="user">Utilisateur</MenuItem>
            </Select>
          </FormControl>

          {/* Favorites Toggle - REMOVED */}
          {/* <Button
            variant={showFavoritesOnly ? 'contained' : 'outlined'}
            size="medium"
            startIcon={<FontAwesome icon={faStar} width={16} />}
            onClick={() => setShowFavoritesOnly(!showFavoritesOnly)}
            sx={{ 
              minHeight: 44,
              px: 3,
              borderRadius: 2,
              textTransform: 'none',
              fontWeight: 500
            }}
          >
            Favoris
          </Button> */}

          <Box sx={{ flexGrow: 1 }} />

          {/* Export Excel */}
          <Button
            variant="outlined"
            size="medium"
            startIcon={<FontAwesome icon={faFileExcel} width={16} />}
            onClick={handleExportExcel}
            sx={{
              minHeight: 44,
              px: 3,
              borderRadius: 2,
              textTransform: 'none',
              fontWeight: 500
            }}
          >
            Export Excel
          </Button>

          {/* View Mode Toggle */}
          <ToggleButtonGroup
            value={viewMode}
            exclusive
            onChange={(_, newMode) => newMode && setViewMode(newMode)}
            size="medium"
            sx={{
              '& .MuiToggleButton-root': {
                minHeight: 44,
                px: 2,
                borderRadius: 2
              }
            }}
          >
            <ToggleButton value="grid">
              <FontAwesome icon={faGrip} width={16} />
            </ToggleButton>
            <ToggleButton value="list">
              <FontAwesome icon={faList} width={16} />
            </ToggleButton>
          </ToggleButtonGroup>
        </Stack>
      </Box>

      {/* Selection Info */}
      <ConditionalComponent isValid={selectedItems.length > 0}>
        <Box sx={{ mb: 3, p: 3, bgcolor: 'primary.lighter', borderRadius: 2, boxShadow: 1 }}>
          <Stack direction="row" alignItems="center" justifyContent="space-between">
            <Typography variant="h6" sx={{ fontWeight: 600, color: 'primary.main' }}>
              {selectedItems.length} élément(s) sélectionné(s)
            </Typography>
            <Stack direction="row" spacing={2}>
              <Button
                size="medium"
                onClick={selectAll}
                sx={{
                  minHeight: 40,
                  borderRadius: 2,
                  textTransform: 'none'
                }}
              >
                {selectedItems.length === filteredAndSortedItems.length ? 'Tout désélectionner' : 'Tout sélectionner'}
              </Button>
              <Button
                size="medium"
                variant="outlined"
                onClick={() => {
                  // Download all selected files
                  const selectedFilesToDownload = filteredAndSortedItems.filter(item =>
                    selectedItems.includes(item.id) && item.type === 'file'
                  );
                  selectedFilesToDownload.forEach(file => handleDownload(file));
                }}
                sx={{
                  minHeight: 40,
                  borderRadius: 2,
                  textTransform: 'none'
                }}
              >
                Télécharger
              </Button>
              <Button
                size="medium"
                variant="outlined"
                color="error"
                onClick={() => handleDeleteClick(selectedItems)}
                sx={{
                  minHeight: 40,
                  borderRadius: 2,
                  textTransform: 'none'
                }}
              >
                Supprimer
              </Button>
            </Stack>
          </Stack>
        </Box>
      </ConditionalComponent>

      {/* File/Folder Display */}
      <Box sx={{
        flex: 1,
        overflow: 'auto',
        bgcolor: 'white',
        borderRadius: 2,
        boxShadow: 1,
        p: 3,
        position: 'relative'
      }}>
        <ConditionalComponent isValid={loading}>
          <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100%' }}>
            <Typography variant="h6" color="text.secondary">
              ⏳ Chargement...
            </Typography>
          </Box>
        </ConditionalComponent>

        <ConditionalComponent isValid={!loading && filteredAndSortedItems.length === 0}>
          <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100%', flexDirection: 'column' }}>
            <Typography variant="h6" color="text.secondary" sx={{ mb: 2 }}>
              📂 Aucun document ou dossier
            </Typography>
            <Typography variant="body2" color="text.secondary">
              Cliquez sur &quot;+ Dossier&quot; ou &quot;+ Fichier&quot; pour commencer
            </Typography>
          </Box>
        </ConditionalComponent>

        <ConditionalComponent isValid={!loading && filteredAndSortedItems.length > 0}>
          <ConditionalComponent isValid={viewMode === 'grid'}>
            {renderGridView()}
          </ConditionalComponent>
          <ConditionalComponent isValid={viewMode === 'list'}>
            {renderListView()}
          </ConditionalComponent>
        </ConditionalComponent>
      </Box>

      {/* Context Menu */}
      <Menu
        anchorEl={contextMenuAnchor}
        open={Boolean(contextMenuAnchor)}
        onClose={() => setContextMenuAnchor(null)}
        sx={{
          '& .MuiPaper-root': {
            borderRadius: 2,
            minWidth: 200,
            boxShadow: '0 10px 40px rgba(0,0,0,0.15)',
            border: '1px solid',
            borderColor: 'divider'
          }
        }}
      >
        {/* Only show "Modifier" for Word and Excel files */}
        <ConditionalComponent isValid={canEditItem(contextMenuItem)}>
          <MenuItem
            onClick={() => {
              if (contextMenuItem) {
                handleEdit(contextMenuItem);
              }
              setContextMenuAnchor(null);
            }}
            sx={{
              minHeight: 48,
              px: 2,
              '&:hover': { bgcolor: 'action.hover' }
            }}
          >
            <ListItemIcon><FontAwesome icon={faEdit} width={16} /></ListItemIcon>
            <ListItemText
              primary="Modifier"
              primaryTypographyProps={{ fontSize: '0.95rem', fontWeight: 500 }}
            />
          </MenuItem>
        </ConditionalComponent>
        <MenuItem
          onClick={() => {
            setRenameDialogOpen(true);
            setContextMenuAnchor(null);
          }}
          sx={{
            minHeight: 48,
            px: 2,
            '&:hover': { bgcolor: 'action.hover' }
          }}
        >
          <ListItemIcon><FontAwesome icon={faPen} width={16} /></ListItemIcon>
          <ListItemText
            primary="Renommer"
            primaryTypographyProps={{ fontSize: '0.95rem', fontWeight: 500 }}
          />
        </MenuItem>
        <MenuItem
          onClick={() => {
            if (contextMenuItem) {
              handleDownload(contextMenuItem);
            }
            setContextMenuAnchor(null);
          }}
          sx={{
            minHeight: 48,
            px: 2,
            '&:hover': { bgcolor: 'action.hover' }
          }}
        >
          <ListItemIcon><FontAwesome icon={faDownload} width={16} /></ListItemIcon>
          <ListItemText
            primary="Télécharger"
            primaryTypographyProps={{ fontSize: '0.95rem', fontWeight: 500 }}
          />
        </MenuItem>
        <MenuItem
          onClick={() => {
            if (contextMenuItem) {
              handleDeleteClick([contextMenuItem.id]);
              setContextMenuAnchor(null);
            }
          }}
          sx={{
            minHeight: 48,
            px: 2,
            color: 'error.main',
            '&:hover': { bgcolor: 'error.lighter' }
          }}
        >
          <ListItemIcon><FontAwesome icon={faTrash} width={16} /></ListItemIcon>
          <ListItemText
            primary="Supprimer"
            primaryTypographyProps={{ fontSize: '0.95rem', fontWeight: 500 }}
          />
        </MenuItem>
      </Menu>

      {/* Dialogs */}
      <AddFolderDialog
        open={addFolderOpen}
        onClose={() => setAddFolderOpen(false)}
        onAdd={addFolder}
        currentPath={currentPath}
      />

      <UploadFileDialog
        open={uploadFileOpen}
        onClose={() => setUploadFileOpen(false)}
        onUpload={handleFileUpload}
        currentPath={currentPath}
      />

      <RenameDialog
        open={renameDialogOpen}
        onClose={() => setRenameDialogOpen(false)}
        onRename={handleRename}
        item={contextMenuItem}
      />

      <SimpleDocumentEditor
        open={editDialogOpen}
        onClose={() => {
          setEditDialogOpen(false);
          setEditingDocument(null);
        }}
        document={editingDocument}
        onSave={handleDocumentSave}
      />

      {/* Delete Confirmation Dialog */}
      <Dialog
        open={deleteConfirmOpen}
        onClose={handleDeleteCancel}
        maxWidth="sm"
        fullWidth
        PaperProps={{
          sx: {
            borderRadius: 3,
            boxShadow: '0 10px 40px rgba(0,0,0,0.2)'
          }
        }}
      >
        <DialogTitle
          sx={{
            fontSize: '1.25rem',
            fontWeight: 600,
            color: 'error.main',
            display: 'flex',
            alignItems: 'center',
            gap: 1.5,
            pb: 2
          }}
        >
          <FontAwesome icon={faTrash} width={24} />
          Confirmer la suppression
        </DialogTitle>
        <DialogContent>
          <DialogContentText sx={{ fontSize: '1rem', color: 'text.primary' }}>
            <ConditionalComponent isValid={itemsToDelete.length === 1}>
              <>
                Êtes-vous sûr de vouloir supprimer cet élément ?
                <br />
                <Box component="span" sx={{ fontWeight: 600, color: 'text.primary', mt: 1, display: 'block' }}>
                  {contextMenuItem?.name || 'Élément sélectionné'}
                </Box>
              </>
            </ConditionalComponent>
            <ConditionalComponent isValid={itemsToDelete.length !== 1}>
              <>
                Êtes-vous sûr de vouloir supprimer{' '}
                <Box component="span" sx={{ fontWeight: 600, color: 'error.main' }}>
                  {itemsToDelete.length} éléments
                </Box>{' '}
                ?
              </>
            </ConditionalComponent>
            <Box
              sx={{
                mt: 2,
                p: 2,
                bgcolor: 'error.lighter',
                borderRadius: 2,
                borderLeft: 4,
                borderColor: 'error.main'
              }}
            >
              <Typography variant="body2" sx={{ color: 'error.dark', fontWeight: 500 }}>
                ⚠️ Cette action est irréversible
              </Typography>
              <Typography variant="caption" sx={{ color: 'error.dark', mt: 0.5, display: 'block' }}>
                <ConditionalComponent isValid={itemsToDelete.length === 1}>
                  Les fichiers et dossiers supprimés ne pourront pas être récupérés.
                </ConditionalComponent>
                <ConditionalComponent isValid={itemsToDelete.length !== 1}>
                  Tous les fichiers et dossiers sélectionnés seront définitivement supprimés.
                </ConditionalComponent>
              </Typography>
            </Box>
          </DialogContentText>
        </DialogContent>
        <DialogActions sx={{ px: 3, pb: 3, pt: 2 }}>
          <Button
            onClick={handleDeleteCancel}
            variant="outlined"
            sx={{
              borderRadius: 2,
              textTransform: 'none',
              fontWeight: 500,
              px: 3,
              py: 1
            }}
          >
            Annuler
          </Button>
          <Button
            onClick={handleDeleteConfirm}
            variant="contained"
            color="error"
            sx={{
              borderRadius: 2,
              textTransform: 'none',
              fontWeight: 600,
              px: 3,
              py: 1
            }}
            startIcon={<FontAwesome icon={faTrash} width={16} />}
          >
            Supprimer
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
} 