import { toast } from "@xtablo/shared";
import { UserTablo } from "@xtablo/shared/types/tablos.types";
import { Button } from "@xtablo/ui/components/button";
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from "@xtablo/ui/components/collapsible";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@xtablo/ui/components/dialog";
import { Input } from "@xtablo/ui/components/input";
import { TypographyH3, TypographyMuted } from "@xtablo/ui/components/typography";
import {
  ChevronDownIcon,
  ChevronRightIcon,
  DownloadIcon,
  FolderIcon,
  FolderPlusIcon,
  PencilIcon,
  Trash2Icon,
} from "lucide-react";
import { useMemo, useRef, useState } from "react";
import {
  useCreateTabloFile,
  useDeleteTabloFile,
  useDownloadTabloFile,
  useTabloFileNames,
} from "../hooks/tablo_data";
import {
  extractFolderIdFromFileName,
  getFileNameWithoutFolder,
  getFolderFilePrefix,
  TabloFolder,
  useCreateTabloFolder,
  useDeleteTabloFolder,
  useTabloFolders,
  useUpdateTabloFolder,
} from "../hooks/tablo_folders";
import { useIsReadOnlyUser, useUser } from "../providers/UserStoreProvider";
import { TabloHeaderActions } from "./TabloHeaderActions";

interface TabloFilesSectionProps {
  tablo: UserTablo;
  isAdmin: boolean;
}

// Helper to get file icon color based on extension
const getFileIconProps = (fileName: string) => {
  const fileExtension = fileName.split(".").pop()?.toLowerCase() || "";
  const isImage = ["jpg", "jpeg", "png", "gif", "webp", "svg"].includes(fileExtension);
  const isPdf = fileExtension === "pdf";
  const isText = ["txt", "md", "json", "csv"].includes(fileExtension);

  if (isImage) return { bgColor: "bg-purple-500 hover:bg-purple-600", type: "image" as const };
  if (isPdf) return { bgColor: "bg-red-500 hover:bg-red-600", type: "pdf" as const };
  if (isText) return { bgColor: "bg-blue-500 hover:bg-blue-600", type: "text" as const };
  return { bgColor: "bg-gray-500 hover:bg-gray-600", type: "other" as const };
};

// File Icon Component
const FileIcon = ({ type }: { type: "image" | "pdf" | "text" | "other" }) => {
  if (type === "image") {
    return (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path
          strokeLinecap="round"
          strokeLinejoin="round"
          strokeWidth={2}
          d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"
        />
      </svg>
    );
  }
  if (type === "pdf") {
    return (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path
          strokeLinecap="round"
          strokeLinejoin="round"
          strokeWidth={2}
          d="M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z"
        />
      </svg>
    );
  }
  return (
    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path
        strokeLinecap="round"
        strokeLinejoin="round"
        strokeWidth={2}
        d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
      />
    </svg>
  );
};

// File Item Component
const FileItem = ({
  displayName,
  canDelete,
  onDownload,
  onDelete,
  isDownloading,
  isDeleting,
}: {
  displayName: string;
  canDelete: boolean;
  onDownload: () => void;
  onDelete: () => void;
  isDownloading: boolean;
  isDeleting: boolean;
}) => {
  const fileExtension = displayName.split(".").pop()?.toLowerCase() || "";
  const { bgColor, type } = getFileIconProps(displayName);

  return (
    <div className="flex items-center space-x-3 p-3 bg-muted rounded-lg hover:bg-muted/80 transition-colors group">
      <button
        onClick={onDownload}
        disabled={isDownloading}
        className={`w-10 h-10 rounded-lg flex items-center justify-center text-white text-sm font-medium transition-all hover:scale-105 ${bgColor} ${
          isDownloading ? "opacity-50 cursor-not-allowed" : "cursor-pointer"
        }`}
        title={`Télécharger ${displayName}`}
      >
        {isDownloading ? (
          <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div>
        ) : (
          <FileIcon type={type} />
        )}
      </button>
      <div className="flex-1 min-w-0">
        <p className="text-sm font-medium text-foreground truncate" title={displayName}>
          {displayName}
        </p>
        <p className="text-xs text-muted-foreground uppercase">{fileExtension || "Fichier"}</p>
      </div>
      <div className="flex items-center space-x-1">
        <Button
          size="sm"
          variant="ghost"
          onClick={onDownload}
          disabled={isDownloading}
          className="p-2 text-gray-400 hover:text-blue-600 hover:bg-blue-50 dark:hover:text-blue-400 dark:hover:bg-blue-900/20 transition-colors"
          aria-label={`Télécharger ${displayName}`}
        >
          {isDownloading ? (
            <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-500"></div>
          ) : (
            <DownloadIcon className="w-4 h-4" />
          )}
        </Button>
        {canDelete && (
          <Button
            size="sm"
            variant="ghost"
            onClick={onDelete}
            disabled={isDeleting}
            className="p-2 text-gray-400 hover:text-red-600 hover:bg-red-50 dark:hover:text-red-400 dark:hover:bg-red-900/20 transition-colors"
            aria-label={`Supprimer ${displayName}`}
          >
            {isDeleting ? (
              <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-red-500"></div>
            ) : (
              <Trash2Icon className="w-4 h-4" />
            )}
          </Button>
        )}
      </div>
    </div>
  );
};

// Folder Create/Edit Dialog
const FolderDialog = ({
  isOpen,
  onClose,
  onSave,
  folder,
  isLoading,
}: {
  isOpen: boolean;
  onClose: () => void;
  onSave: (name: string, description: string) => void;
  folder?: TabloFolder | null;
  isLoading: boolean;
}) => {
  const [name, setName] = useState(folder?.name || "");
  const [description, setDescription] = useState(folder?.description || "");

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (name.trim()) {
      onSave(name.trim(), description.trim());
    }
  };

  // Reset form when dialog opens
  const handleOpenChange = (open: boolean) => {
    if (open) {
      setName(folder?.name || "");
      setDescription(folder?.description || "");
    } else {
      onClose();
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={handleOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{folder ? "Modifier le livrable" : "Nouveau livrable"}</DialogTitle>
          <DialogDescription>
            {folder
              ? "Modifiez les informations du livrable attendu."
              : "Créez un nouveau livrable attendu pour organiser les fichiers de ce tablo."}
          </DialogDescription>
        </DialogHeader>
        <form onSubmit={handleSubmit}>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <label htmlFor="folder-name" className="text-sm font-medium text-foreground">
                Nom du livrable *
              </label>
              <Input
                id="folder-name"
                value={name}
                onChange={(e) => setName(e.target.value)}
                placeholder="ex: Maquettes finales, Documentation technique..."
                required
              />
            </div>
            <div className="space-y-2">
              <label htmlFor="folder-description" className="text-sm font-medium text-foreground">
                Description (optionnel)
              </label>
              <Input
                id="folder-description"
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                placeholder="Décrivez ce qui est attendu dans ce livrable..."
              />
            </div>
          </div>
          <DialogFooter>
            <Button type="button" variant="outline" onClick={onClose} disabled={isLoading}>
              Annuler
            </Button>
            <Button type="submit" disabled={!name.trim() || isLoading}>
              {isLoading ? (
                <>
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
                  {folder ? "Mise à jour..." : "Création..."}
                </>
              ) : folder ? (
                "Enregistrer"
              ) : (
                "Créer le livrable"
              )}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
};

// Folder Component with collapsible content
const FolderSection = ({
  folder,
  files,
  isAdmin,
  isReadOnly,
  isOpen,
  onToggle,
  onEdit,
  onDelete,
  onUploadFile,
  onDownloadFile,
  onDeleteFile,
  downloadingFile,
  deletingFile,
  isUploading,
}: {
  folder: TabloFolder;
  files: string[];
  isAdmin: boolean;
  isReadOnly: boolean;
  isOpen: boolean;
  onToggle: () => void;
  onEdit: () => void;
  onDelete: () => void;
  onUploadFile: (file: File) => void;
  onDownloadFile: (fileName: string) => void;
  onDeleteFile: (fileName: string) => void;
  downloadingFile: string | null;
  deletingFile: string | null;
  isUploading: boolean;
}) => {
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    const maxSize = 20 * 1024 * 1024;
    if (file.size > maxSize) {
      toast.add(
        { title: "Erreur", description: "Le fichier ne peut pas dépasser 20MB", type: "error" },
        { timeout: 5000 }
      );
      return;
    }

    onUploadFile(file);
    if (fileInputRef.current) {
      fileInputRef.current.value = "";
    }
  };

  return (
    <Collapsible open={isOpen} onOpenChange={onToggle}>
      <div className="bg-card rounded-lg border border-border overflow-hidden">
        <CollapsibleTrigger asChild>
          <button className="w-full flex items-center justify-between p-4 hover:bg-muted/50 transition-colors text-left">
            <div className="flex items-center space-x-3">
              <div className="w-10 h-10 rounded-lg bg-amber-500/10 flex items-center justify-center">
                <FolderIcon className="w-5 h-5 text-amber-600 dark:text-amber-400" />
              </div>
              <div>
                <div className="flex items-center space-x-2">
                  <h4 className="font-semibold text-foreground">{folder.name}</h4>
                  <span className="text-xs text-muted-foreground bg-muted px-2 py-0.5 rounded-full">
                    {files.length} fichier{files.length !== 1 ? "s" : ""}
                  </span>
                </div>
                {folder.description && (
                  <p className="text-sm text-muted-foreground mt-0.5">{folder.description}</p>
                )}
              </div>
            </div>
            <div className="flex items-center space-x-2">
              {isAdmin && !isReadOnly && (
                <>
                  <Button
                    size="sm"
                    variant="ghost"
                    onClick={(e) => {
                      e.stopPropagation();
                      onEdit();
                    }}
                    className="p-2 text-gray-400 hover:text-blue-600 hover:bg-blue-50 dark:hover:text-blue-400 dark:hover:bg-blue-900/20"
                  >
                    <PencilIcon className="w-4 h-4" />
                  </Button>
                  <Button
                    size="sm"
                    variant="ghost"
                    onClick={(e) => {
                      e.stopPropagation();
                      onDelete();
                    }}
                    className="p-2 text-gray-400 hover:text-red-600 hover:bg-red-50 dark:hover:text-red-400 dark:hover:bg-red-900/20"
                  >
                    <Trash2Icon className="w-4 h-4" />
                  </Button>
                </>
              )}
              {isOpen ? (
                <ChevronDownIcon className="w-5 h-5 text-muted-foreground" />
              ) : (
                <ChevronRightIcon className="w-5 h-5 text-muted-foreground" />
              )}
            </div>
          </button>
        </CollapsibleTrigger>
        <CollapsibleContent>
          <div className="border-t border-border p-4 space-y-4">
            {/* File Upload Area */}
            <div>
              <input
                ref={fileInputRef}
                type="file"
                onChange={handleFileSelect}
                className="hidden"
                accept="*/*"
              />
              <button
                type="button"
                onClick={() => fileInputRef.current?.click()}
                disabled={isUploading}
                className="w-full py-4 border-2 border-dashed border-gray-300 dark:border-gray-600 hover:border-amber-400 dark:hover:border-amber-500 bg-gray-50 dark:bg-gray-800/50 hover:bg-amber-50 dark:hover:bg-amber-900/20 transition-colors rounded-md cursor-pointer flex items-center justify-center space-x-2 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {isUploading ? (
                  <>
                    <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-amber-500"></div>
                    <span className="text-sm text-muted-foreground">Téléchargement...</span>
                  </>
                ) : (
                  <>
                    <svg
                      className="w-5 h-5 text-gray-400"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M12 6v6m0 0v6m0-6h6m-6 0H6"
                      />
                    </svg>
                    <span className="text-sm text-muted-foreground">
                      Ajouter un fichier à ce livrable
                    </span>
                  </>
                )}
              </button>
            </div>

            {/* Files List */}
            {files.length > 0 ? (
              <div className="space-y-2">
                {files.map((fileName) => (
                  <FileItem
                    key={fileName}
                    displayName={getFileNameWithoutFolder(fileName)}
                    canDelete={true}
                    onDownload={() => onDownloadFile(fileName)}
                    onDelete={() => onDeleteFile(fileName)}
                    isDownloading={downloadingFile === fileName}
                    isDeleting={deletingFile === fileName}
                  />
                ))}
              </div>
            ) : (
              <div className="text-center py-4">
                <p className="text-sm text-muted-foreground">Aucun fichier dans ce livrable</p>
              </div>
            )}
          </div>
        </CollapsibleContent>
      </div>
    </Collapsible>
  );
};

export const TabloFilesSection = ({ tablo, isAdmin }: TabloFilesSectionProps) => {
  const currentUser = useUser();
  const {
    data: fileData,
    isLoading: filesLoading,
    error: filesError,
  } = useTabloFileNames(tablo.id);
  const {
    data: foldersData,
    isLoading: foldersLoading,
    error: foldersError,
  } = useTabloFolders(tablo.id);

  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [isUploading, setIsUploading] = useState(false);
  const [uploadingToFolder, setUploadingToFolder] = useState<string | null>(null);
  const [deletingFile, setDeletingFile] = useState<string | null>(null);
  const [downloadingFile, setDownloadingFile] = useState<string | null>(null);
  const [error, setError] = useState("");
  const [openFolders, setOpenFolders] = useState<Set<string>>(new Set());
  const [isFolderDialogOpen, setIsFolderDialogOpen] = useState(false);
  const [editingFolder, setEditingFolder] = useState<TabloFolder | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const createFile = useCreateTabloFile();
  const deleteFile = useDeleteTabloFile();
  const downloadFile = useDownloadTabloFile();
  const createFolder = useCreateTabloFolder();
  const updateFolder = useUpdateTabloFolder();
  const deleteFolder = useDeleteTabloFolder();
  const isReadOnly = useIsReadOnlyUser();
  const folders = foldersData?.folders || [];
  const folderIds = useMemo(() => new Set(folders.map((folder) => folder.id)), [folders]);

  // Organize files by folder
  const { filesInFolders, unorganizedFiles } = useMemo(() => {
    if (!fileData?.fileNames) {
      return { filesInFolders: new Map<string, string[]>(), unorganizedFiles: [] };
    }

    const filesInFolders = new Map<string, string[]>();
    const unorganizedFiles: string[] = [];

    for (const fileName of fileData.fileNames) {
      // Skip metadata files
      if (fileName.startsWith(".")) continue;

      const folderId = extractFolderIdFromFileName(fileName);
      if (folderId && folderIds.has(folderId)) {
        const existing = filesInFolders.get(folderId) || [];
        existing.push(fileName);
        filesInFolders.set(folderId, existing);
      } else {
        unorganizedFiles.push(fileName);
      }
    }

    return { filesInFolders, unorganizedFiles };
  }, [fileData?.fileNames, folderIds]);

  const toggleFolder = (folderId: string) => {
    setOpenFolders((prev) => {
      const next = new Set(prev);
      if (next.has(folderId)) {
        next.delete(folderId);
      } else {
        next.add(folderId);
      }
      return next;
    });
  };

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    const maxSize = 20 * 1024 * 1024;
    if (file.size > maxSize) {
      setError("Le fichier ne peut pas dépasser 20MB");
      return;
    }

    setError("");
    setSelectedFile(file);
  };

  const uploadFile = async (file: File, folderId?: string) => {
    if (!tablo.id) return;

    const targetFolderId = folderId;
    if (targetFolderId) {
      setUploadingToFolder(targetFolderId);
    } else {
      setIsUploading(true);
    }

    try {
      const reader = new FileReader();
      reader.onload = async (e) => {
        try {
          const content = e.target?.result as string;
          const fileName = targetFolderId
            ? `${getFolderFilePrefix(targetFolderId)}${file.name}`
            : file.name;

          await createFile.mutateAsync({
            tabloId: tablo.id,
            fileName,
            data: {
              content,
              contentType: file.type || "application/octet-stream",
            },
          });

          setSelectedFile(null);
          if (fileInputRef.current) {
            fileInputRef.current.value = "";
          }
        } catch (uploadError) {
          console.error("Upload error:", uploadError);
        } finally {
          setIsUploading(false);
          setUploadingToFolder(null);
        }
      };

      reader.onerror = () => {
        setIsUploading(false);
        setUploadingToFolder(null);
        toast.add(
          {
            title: "Erreur de lecture",
            description: "Impossible de lire le fichier sélectionné",
            type: "error",
          },
          { timeout: 5000 }
        );
      };

      if (file.type.startsWith("text/") || file.type === "application/json") {
        reader.readAsText(file);
      } else {
        reader.readAsDataURL(file);
      }
    } catch (error) {
      setIsUploading(false);
      setUploadingToFolder(null);
      console.error("Upload error:", error);
    }
  };

  const handleFileUpload = async () => {
    if (!selectedFile) return;
    await uploadFile(selectedFile);
  };

  const cancelFileUpload = () => {
    setSelectedFile(null);
    if (fileInputRef.current) {
      fileInputRef.current.value = "";
    }
  };

  const handleDeleteFile = async (fileName: string) => {
    if (!tablo.id) return;
    const displayName = getFileNameWithoutFolder(fileName);
    if (!window.confirm(`Êtes-vous sûr de vouloir supprimer le fichier "${displayName}" ?`)) {
      return;
    }

    setDeletingFile(fileName);
    try {
      await deleteFile.mutateAsync({ tabloId: tablo.id, fileName });
    } catch (error) {
      console.error("Delete error:", error);
    } finally {
      setDeletingFile(null);
    }
  };

  const handleDownloadFile = async (fileName: string) => {
    if (!tablo.id) return;

    setDownloadingFile(fileName);
    try {
      await downloadFile.mutateAsync({ tabloId: tablo.id, fileName });
    } catch (error) {
      console.error("Download error:", error);
    } finally {
      setDownloadingFile(null);
    }
  };

  const handleCreateFolder = () => {
    setEditingFolder(null);
    setIsFolderDialogOpen(true);
  };

  const handleEditFolder = (folder: TabloFolder) => {
    setEditingFolder(folder);
    setIsFolderDialogOpen(true);
  };

  const handleDeleteFolder = async (folder: TabloFolder) => {
    const filesInFolder = filesInFolders.get(folder.id) || [];
    const confirmMessage =
      filesInFolder.length > 0
        ? `Êtes-vous sûr de vouloir supprimer le livrable "${folder.name}" ? Les ${filesInFolder.length} fichier(s) associé(s) resteront dans le tablo mais ne seront plus organisés.`
        : `Êtes-vous sûr de vouloir supprimer le livrable "${folder.name}" ?`;

    if (!window.confirm(confirmMessage)) return;

    await deleteFolder.mutateAsync({
      tabloId: tablo.id,
      folderId: folder.id,
      folderName: folder.name,
    });
  };

  const handleSaveFolder = async (name: string, description: string) => {
    if (editingFolder) {
      await updateFolder.mutateAsync({
        tabloId: tablo.id,
        folderId: editingFolder.id,
        name,
        description,
      });
    } else {
      await createFolder.mutateAsync({
        tabloId: tablo.id,
        name,
        description,
        createdBy: currentUser?.id || "",
      });
    }
    setIsFolderDialogOpen(false);
    setEditingFolder(null);
  };

  const isLoading = filesLoading || foldersLoading;

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-start">
        <div>
          <TypographyH3 className="text-3xl font-bold text-foreground">Fichiers</TypographyH3>
          <TypographyMuted className="text-muted-foreground mt-1">
            Gérez les fichiers et livrables de ce tablo
          </TypographyMuted>
        </div>
        <TabloHeaderActions tablo={tablo} isAdmin={isAdmin} />
      </div>

      {/* Error Banner */}
      {error && (
        <div className="p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg flex items-center space-x-2">
          <svg
            className="w-5 h-5 text-red-500 shrink-0"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
            />
          </svg>
          <span className="text-red-700 dark:text-red-300 text-sm">{error}</span>
          <button
            onClick={() => setError("")}
            className="ml-auto text-red-500 hover:text-red-700 dark:hover:text-red-300"
          >
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M6 18L18 6M6 6l12 12"
              />
            </svg>
          </button>
        </div>
      )}
      {(filesError || foldersError) && (
        <div className="p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg">
          <span className="text-red-700 dark:text-red-300 text-sm">
            Impossible de charger les fichiers pour ce tablo.
          </span>
        </div>
      )}

      {/* Create Folder Button - Admin Only */}
      {isAdmin && !isReadOnly && (
        <div className="flex justify-end">
          <Button onClick={handleCreateFolder} variant="outline" className="gap-2">
            <FolderPlusIcon className="w-4 h-4" />
            Nouveau livrable
          </Button>
        </div>
      )}

      {isLoading ? (
        <div className="flex items-center justify-center p-8">
          <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-blue-500"></div>
          <span className="ml-3 text-sm text-gray-500 dark:text-gray-400">Chargement...</span>
        </div>
      ) : (
        <>
          {/* Folders Section */}
          {folders.length > 0 && (
            <div className="space-y-4">
              <h3 className="text-lg font-semibold text-foreground">
                Livrables attendus
                <span className="ml-2 text-sm font-normal text-muted-foreground">
                  ({folders.length})
                </span>
              </h3>
              <div className="space-y-3">
                {folders.map((folder) => (
                  <FolderSection
                    key={folder.id}
                    folder={folder}
                    files={filesInFolders.get(folder.id) || []}
                    isAdmin={isAdmin}
                    isReadOnly={isReadOnly}
                    isOpen={openFolders.has(folder.id)}
                    onToggle={() => toggleFolder(folder.id)}
                    onEdit={() => handleEditFolder(folder)}
                    onDelete={() => handleDeleteFolder(folder)}
                    onUploadFile={(file) => uploadFile(file, folder.id)}
                    onDownloadFile={handleDownloadFile}
                    onDeleteFile={handleDeleteFile}
                    downloadingFile={downloadingFile}
                    deletingFile={deletingFile}
                    isUploading={uploadingToFolder === folder.id}
                  />
                ))}
              </div>
            </div>
          )}

          {/* Unorganized Files Section */}
          <div className="bg-card rounded-lg border border-border p-6">
            <div className="flex items-center space-x-2 mb-4">
              <svg
                className="w-5 h-5 text-green-600 dark:text-green-400"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M12 6v6m0 0v6m0-6h6m-6 0H6"
                />
              </svg>
              <h3 className="text-lg font-semibold text-foreground">
                {folders.length > 0 ? "Autres fichiers" : "Fichiers"}
              </h3>
              {unorganizedFiles.length > 0 && (
                <span className="text-sm text-muted-foreground">({unorganizedFiles.length})</span>
              )}
            </div>

            {/* File Upload Area */}
            {!selectedFile ? (
              <div className="space-y-3">
                <input
                  ref={fileInputRef}
                  type="file"
                  onChange={handleFileSelect}
                  className="hidden"
                  accept="*/*"
                />
                <button
                  type="button"
                  onClick={() => fileInputRef.current?.click()}
                  className="w-full justify-center py-8 border-2 border-dashed border-gray-300 dark:border-gray-600 hover:border-blue-400 dark:hover:border-blue-500 bg-gray-50 dark:bg-gray-800/50 hover:bg-blue-50 dark:hover:bg-blue-900/20 transition-colors rounded-md cursor-pointer inline-flex items-center"
                >
                  <div className="flex flex-col items-center space-y-2">
                    <svg
                      className="w-8 h-8 text-gray-400 dark:text-gray-500"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"
                      />
                    </svg>
                    <div className="text-center">
                      <span className="text-sm font-medium text-gray-700 dark:text-gray-300">
                        Cliquez pour sélectionner un fichier
                      </span>
                    </div>
                  </div>
                </button>
              </div>
            ) : (
              <div className="space-y-3">
                <div className="flex items-center space-x-3 p-3 bg-blue-50 dark:bg-blue-900/20 rounded-md">
                  <div className="w-8 h-8 bg-blue-500 rounded-full flex items-center justify-center text-white text-sm font-medium">
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
                      />
                    </svg>
                  </div>
                  <div className="flex-1">
                    <p className="text-sm font-medium text-gray-900 dark:text-white">
                      {selectedFile.name}
                    </p>
                    <p className="text-xs text-gray-500 dark:text-gray-400">
                      {(selectedFile.size / 1024 / 1024).toFixed(2)} MB
                    </p>
                  </div>
                </div>

                <div className="flex space-x-3">
                  <button
                    type="button"
                    onClick={handleFileUpload}
                    disabled={isUploading}
                    className="flex-1 px-4 py-2.5 text-sm font-medium text-white bg-green-600 hover:bg-green-700 disabled:bg-gray-400 disabled:cursor-not-allowed rounded-lg transition-colors flex items-center justify-center space-x-2 shadow-sm"
                  >
                    {isUploading ? (
                      <>
                        <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                        <span>Ajout en cours...</span>
                      </>
                    ) : (
                      <>
                        <svg
                          className="w-4 h-4"
                          fill="none"
                          stroke="currentColor"
                          viewBox="0 0 24 24"
                        >
                          <path
                            strokeLinecap="round"
                            strokeLinejoin="round"
                            strokeWidth={2}
                            d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"
                          />
                        </svg>
                        <span>Ajouter le fichier</span>
                      </>
                    )}
                  </button>
                  <button
                    type="button"
                    onClick={cancelFileUpload}
                    disabled={isUploading}
                    className="px-4 py-2.5 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-600 disabled:opacity-50 disabled:cursor-not-allowed rounded-lg transition-colors"
                  >
                    Annuler
                  </button>
                </div>
              </div>
            )}

            <p className="text-xs text-gray-500 dark:text-gray-400 mt-2">
              Taille maximale par fichier: 20MB
            </p>

            {/* Unorganized Files List */}
            {unorganizedFiles.length > 0 && (
              <div className="mt-6 space-y-2">
                {unorganizedFiles.map((fileName) => (
                  <FileItem
                    key={fileName}
                    displayName={getFileNameWithoutFolder(fileName)}
                    canDelete={true}
                    onDownload={() => handleDownloadFile(fileName)}
                    onDelete={() => handleDeleteFile(fileName)}
                    isDownloading={downloadingFile === fileName}
                    isDeleting={deletingFile === fileName}
                  />
                ))}
              </div>
            )}

            {/* Empty State */}
            {unorganizedFiles.length === 0 && !selectedFile && folders.length === 0 && (
              <div className="text-center py-8 mt-4">
                <svg
                  className="w-12 h-12 text-gray-300 dark:text-gray-600 mx-auto mb-3"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2H5a2 2 0 00-2-2z"
                  />
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M8 5a2 2 0 012-2h2a2 2 0 012 2v0H8v0z"
                  />
                </svg>
                <p className="text-sm text-gray-500 dark:text-gray-400">
                  Aucun fichier dans ce tablo
                </p>
                <p className="text-xs text-gray-400 dark:text-gray-500 mt-1">
                  Ajoutez votre premier fichier ci-dessus
                </p>
              </div>
            )}
          </div>
        </>
      )}

      {/* Folder Dialog */}
      <FolderDialog
        isOpen={isFolderDialogOpen}
        onClose={() => {
          setIsFolderDialogOpen(false);
          setEditingFolder(null);
        }}
        onSave={handleSaveFolder}
        folder={editingFolder}
        isLoading={createFolder.isPending || updateFolder.isPending}
      />
    </div>
  );
};
