// File Path: monorepo/native/desktop/maplefile/frontend/src/pages/User/FileManager/Collections/CollectionDetails.jsx
import { useState, useEffect, useCallback } from "react";
import { useNavigate, useParams, useLocation } from "react-router-dom";
import Navigation from "../../../../components/Navigation";
import Page from "../../../../components/Page";
import {
  GetCollection,
  ListCollections,
  ListFilesByCollection,
  OnloadFile,
  DownloadFile,
  OpenFile,
  OffloadFile,
  ListTags,
  AssignTagToCollection,
  UnassignTagFromCollection,
  DeleteCollection,
} from "../../../../../wailsjs/go/app/Application";
import "../../Dashboard/Dashboard.css";

function CollectionDetails() {
  const navigate = useNavigate();
  const { collectionId } = useParams();
  const location = useLocation();

  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState("");
  const [collection, setCollection] = useState(null);
  const [files, setFiles] = useState([]);
  const [subCollections, setSubCollections] = useState([]);
  const [searchQuery, setSearchQuery] = useState("");
  const [allTags, setAllTags] = useState([]);
  const [selectedTagIds, setSelectedTagIds] = useState([]);
  const [showTagFilter, setShowTagFilter] = useState(false);

  // Collection tag editor state
  const [showCollectionTagEditor, setShowCollectionTagEditor] = useState(false);
  const [selectedCollectionTagIds, setSelectedCollectionTagIds] = useState([]);
  const [isSavingCollectionTags, setIsSavingCollectionTags] = useState(false);
  const [collectionTagError, setCollectionTagError] = useState("");

  // Delete confirmation state
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);

  // Load collection details
  const loadCollection = useCallback(async () => {
    // Validate collectionId before making API call
    if (!collectionId || collectionId === "undefined" || collectionId === "null") {
      console.error("❌ Invalid collection ID:", collectionId);
      setError("Invalid collection ID");
      setIsLoading(false);
      return;
    }

    setIsLoading(true);
    setError("");

    try {
      console.log("🔄 Loading collection details...", collectionId);
      const collectionData = await GetCollection(collectionId);
      console.log("✅ Collection loaded:", collectionData);
      console.log("✅ Collection tags:", collectionData?.tags);
      console.log("✅ Collection tags count:", collectionData?.tags?.length || 0);
      setCollection(collectionData);
    } catch (err) {
      console.error("❌ Failed to load collection:", collectionId, err);
      setError(`Failed to load collection: ${err.message || "Unknown error"}`);
    } finally {
      setIsLoading(false);
    }
  }, [collectionId]);

  // Load files in this collection
  const loadFiles = useCallback(async () => {
    try {
      console.log("🔄 Loading files for collection...", collectionId);
      const filesData = await ListFilesByCollection(collectionId);
      console.log("✅ Files loaded:", filesData ? filesData.length : 0);
      setFiles(filesData || []);
    } catch (err) {
      console.error("❌ Failed to load files:", err);
      // Don't set error - files might just be empty
      setFiles([]);
    }
  }, [collectionId]);

  // Load sub-collections (collections where parent_id = this collectionId)
  const loadSubCollections = useCallback(async () => {
    try {
      console.log("🔄 Loading sub-collections...", collectionId);
      const allCollections = await ListCollections();
      const subs = allCollections.filter(
        (col) => col.parent_id === collectionId
      );
      console.log("✅ Sub-collections found:", subs ? subs.length : 0);
      setSubCollections(subs || []);
    } catch (err) {
      console.error("❌ Failed to load sub-collections:", err);
      setSubCollections([]);
    }
  }, [collectionId]);

  // Load all available tags for filtering
  const loadTags = useCallback(async () => {
    try {
      console.log("🔄 Loading tags for filter...");
      const tags = await ListTags();
      console.log("✅ Tags loaded:", tags ? tags.length : 0);
      setAllTags(tags || []);
    } catch (err) {
      console.error("❌ Failed to load tags:", err);
      setAllTags([]);
    }
  }, []);

  // Initial load - wait for Wails to be ready
  useEffect(() => {
    // Check if Wails bindings are available
    if (typeof window !== 'undefined' && window.go && window.go.app && window.go.app.Application) {
      loadCollection();
      loadFiles();
      loadSubCollections();
      loadTags();
    } else {
      // Wait for Wails to be ready
      const checkWails = setInterval(() => {
        if (window.go && window.go.app && window.go.app.Application) {
          clearInterval(checkWails);
          loadCollection();
          loadFiles();
          loadSubCollections();
          loadTags();
        }
      }, 100);

      // Cleanup timeout after 10 seconds
      setTimeout(() => clearInterval(checkWails), 10000);

      return () => clearInterval(checkWails);
    }
  }, [loadCollection, loadFiles, loadSubCollections, loadTags]);

  // Refresh on navigation state
  useEffect(() => {
    if (location.state?.refresh) {
      loadCollection();
      loadFiles();
      loadSubCollections();
      // Clear the state
      navigate(location.pathname, { replace: true, state: {} });
    }
  }, [location.state, location.pathname, navigate, loadCollection, loadFiles, loadSubCollections]);

  // Filter by search query and selected tags (multi-tag filtering with AND logic)
  const filteredFiles = files.filter((file) => {
    const matchesSearch = file.filename.toLowerCase().includes(searchQuery.toLowerCase());

    // Apply tag filter (multi-tag filtering with AND logic)
    let matchesTags = true;
    if (selectedTagIds.length > 0) {
      const fileTagIds = (file.tags || []).map(tag => tag.id);
      // Check if file has ALL selected tags
      matchesTags = selectedTagIds.every(tagId => fileTagIds.includes(tagId));
    }

    return matchesSearch && matchesTags;
  });

  const filteredSubCollections = subCollections.filter((col) =>
    col.name.toLowerCase().includes(searchQuery.toLowerCase())
  );

  // State for file operations
  const [loadingFileId, setLoadingFileId] = useState(null);

  // Helper functions
  const formatFileSize = (bytes) => {
    if (!bytes) return "0 B";
    const sizes = ["B", "KB", "MB", "GB"];
    const i = Math.floor(Math.log(bytes) / Math.log(1024));
    return `${Math.round(bytes / Math.pow(1024, i))} ${sizes[i]}`;
  };

  const getTimeAgo = (dateString) => {
    if (!dateString) return "Recently";
    const now = new Date();
    const date = new Date(dateString);
    const diffInMinutes = Math.floor((now - date) / (1000 * 60));

    if (diffInMinutes < 60) return "Just now";
    if (diffInMinutes < 1440) return "Today";
    if (diffInMinutes < 2880) return "Yesterday";
    const diffInDays = Math.floor(diffInMinutes / 1440);
    if (diffInDays < 7) return `${diffInDays} days ago`;
    if (diffInDays < 30) return `${Math.floor(diffInDays / 7)} weeks ago`;
    return `${Math.floor(diffInDays / 30)} months ago`;
  };

  // Get sync status icon and color
  const getSyncStatusInfo = (syncStatus) => {
    switch (syncStatus) {
      case "cloud_only":
        return { icon: "☁️", color: "#2196f3", label: "Cloud Only", tooltip: "File is in the cloud, not downloaded locally" };
      case "local_only":
        return { icon: "💻", color: "#9c27b0", label: "Local Only", tooltip: "File exists only locally, not uploaded to cloud" };
      case "synced":
        return { icon: "✓", color: "#4caf50", label: "Synced", tooltip: "File is synchronized between local and cloud" };
      case "modified_locally":
        return { icon: "⬆️", color: "#ff9800", label: "Modified", tooltip: "Local changes pending upload to cloud" };
      default:
        return { icon: "☁️", color: "#2196f3", label: "Cloud Only", tooltip: "File is in the cloud" };
    }
  };

  // Handle onload file (download for offline access)
  const handleOnloadFile = async (e, fileId) => {
    e.stopPropagation();
    setLoadingFileId(fileId);
    try {
      console.log("🔄 Onloading file for offline access:", fileId);
      const result = await OnloadFile(fileId);
      console.log("✅ File onloaded:", result);
      // Refresh file list to update sync status
      await loadFiles();
    } catch (err) {
      console.error("❌ Failed to onload file:", err);
      setError(err.message || "Failed to download file");
    } finally {
      setLoadingFileId(null);
    }
  };

  // Handle download file (save to user-chosen location)
  const handleDownloadFile = async (e, fileId) => {
    e.stopPropagation();
    setLoadingFileId(fileId);
    try {
      console.log("🔄 Downloading file:", fileId);
      const savePath = await DownloadFile(fileId);
      if (savePath) {
        console.log("✅ File downloaded to:", savePath);
      } else {
        console.log("ℹ️ Download cancelled by user");
      }
    } catch (err) {
      console.error("❌ Failed to download file:", err);
      setError(err.message || "Failed to download file");
    } finally {
      setLoadingFileId(null);
    }
  };

  // Handle open file (open with system default application)
  const handleOpenFile = async (e, fileId) => {
    e.stopPropagation();
    try {
      console.log("🔄 Opening file:", fileId);
      await OpenFile(fileId);
      console.log("✅ File opened");
    } catch (err) {
      console.error("❌ Failed to open file:", err);
      setError(err.message || "Failed to open file");
    }
  };

  // Handle offload file (remove local copy, keep in cloud)
  const handleOffloadFile = async (e, fileId) => {
    e.stopPropagation();
    setLoadingFileId(fileId);
    try {
      console.log("🔄 Offloading file to cloud-only:", fileId);
      await OffloadFile(fileId);
      console.log("✅ File offloaded");
      // Refresh file list to update sync status
      await loadFiles();
    } catch (err) {
      console.error("❌ Failed to offload file:", err);
      setError(err.message || "Failed to offload file");
    } finally {
      setLoadingFileId(null);
    }
  };

  const handleCreateSubCollection = () => {
    navigate("/file-manager/collections/create", {
      state: {
        parentCollectionId: collectionId,
        parentCollectionName: collection?.name || "Parent Collection",
      },
    });
  };

  const handleUploadFile = () => {
    navigate(`/file-manager/upload?collection=${collectionId}`);
  };

  const getBackUrl = () => {
    // If this collection has a valid parent_id, go back to parent
    // Check for truthy value and ensure it's not an empty string or invalid UUID
    const parentId = collection?.parent_id;
    if (parentId && parentId.trim() !== "" && parentId !== "00000000-0000-0000-0000-000000000000") {
      return `/file-manager/collections/${parentId}`;
    }
    // Otherwise go to file manager index
    return "/file-manager";
  };

  const getBackText = () => {
    const parentId = collection?.parent_id;
    if (parentId && parentId.trim() !== "" && parentId !== "00000000-0000-0000-0000-000000000000") {
      return "← Back to Parent Collection";
    }
    return "← Back to File Manager";
  };

  // Collection tag management handlers
  const handleOpenCollectionTagEditor = () => {
    // Set currently selected tags from collection
    const currentTagIds = (collection?.tags || []).map((tag) => tag.id);
    setSelectedCollectionTagIds(currentTagIds);
    setCollectionTagError("");
    setShowCollectionTagEditor(true);
  };

  const handleToggleCollectionTag = (tagId) => {
    setSelectedCollectionTagIds((prev) => {
      if (prev.includes(tagId)) {
        return prev.filter((id) => id !== tagId);
      }
      return [...prev, tagId];
    });
  };

  const handleSaveCollectionTags = async () => {
    setIsSavingCollectionTags(true);
    setCollectionTagError("");

    try {
      const currentTagIds = (collection?.tags || []).map((tag) => tag.id);

      // Find tags to add and remove
      const tagsToAdd = selectedCollectionTagIds.filter((id) => !currentTagIds.includes(id));
      const tagsToRemove = currentTagIds.filter((id) => !selectedCollectionTagIds.includes(id));

      // Add new tags
      for (const tagId of tagsToAdd) {
        await AssignTagToCollection(tagId, collectionId);
      }

      // Remove unselected tags
      for (const tagId of tagsToRemove) {
        await UnassignTagFromCollection(tagId, collectionId);
      }

      // Reload collection to get updated tags
      await loadCollection();
      setShowCollectionTagEditor(false);
    } catch (err) {
      console.error("Failed to save collection tags:", err);
      setCollectionTagError(err.message || "Failed to save tags");
    } finally {
      setIsSavingCollectionTags(false);
    }
  };

  const handleRemoveCollectionTag = async (tagId) => {
    try {
      await UnassignTagFromCollection(tagId, collectionId);
      await loadCollection();
    } catch (err) {
      console.error("Failed to remove tag from collection:", err);
      setError(err.message || "Failed to remove tag");
    }
  };

  const handleDeleteCollection = async () => {
    setIsDeleting(true);
    setError("");

    try {
      await DeleteCollection(collectionId);
      // Navigate back to parent or file manager
      if (collection.parent_id && collection.parent_id !== "00000000-0000-0000-0000-000000000000") {
        navigate(`/file-manager/collections/${collection.parent_id}`, {
          state: { refresh: true },
        });
      } else {
        navigate("/file-manager", {
          state: { refresh: true },
        });
      }
    } catch (err) {
      console.error("Failed to delete collection:", err);
      setError(err.message || "Failed to delete collection");
      setShowDeleteConfirm(false);
    } finally {
      setIsDeleting(false);
    }
  };

  if (isLoading) {
    return (
      <div className="layout">
        <Navigation />
        <div className="main-content">
          <Page title="Loading...">
            <div style={{ textAlign: "center", padding: "40px" }}>
              <div>Loading collection...</div>
            </div>
          </Page>
        </div>
      </div>
    );
  }

  return (
    <div className="layout">
      <Navigation />
      <div className="main-content">
        <Page title={collection?.name || "Collection Details"}>
          {/* Back Button */}
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "20px" }}>
            <button
              onClick={() => navigate(getBackUrl())}
              className="nav-button secondary"
            >
              {getBackText()}
            </button>

            <button
              onClick={() => setShowDeleteConfirm(true)}
              className="nav-button"
              style={{
                background: "#d32f2f",
                color: "white",
                border: "1px solid #c62828",
              }}
            >
              🗑️ Delete Collection
            </button>
          </div>

          {/* Error Display */}
          {error && (
            <div
              style={{
                padding: "15px",
                background: "#ffebee",
                color: "#c62828",
                borderRadius: "4px",
                marginBottom: "20px",
                border: "1px solid #f44336",
              }}
            >
              {error}
            </div>
          )}

          {/* Collection Info */}
          {collection && (
            <div
              style={{
                background: "white",
                padding: "20px",
                borderRadius: "8px",
                border: "1px solid #ddd",
                marginBottom: "30px",
              }}
            >
              <div style={{ display: "flex", alignItems: "center", gap: "15px" }}>
                <div style={{ fontSize: "48px" }}>
                  {collection.custom_icon
                    ? collection.custom_icon
                    : collection.is_shared
                      ? "🔗"
                      : "📁"}
                </div>
                <div style={{ flex: 1 }}>
                  <h2 style={{ margin: 0, marginBottom: "5px", color: "#333" }}>
                    {collection.name}
                  </h2>
                  {collection.description && (
                    <p style={{ margin: 0, color: "#666", fontSize: "14px" }}>
                      {collection.description}
                    </p>
                  )}
                  <div style={{ fontSize: "14px", color: "#666", marginTop: "10px" }}>
                    <div>
                      {collection.file_count || 0}{" "}
                      {collection.file_count === 1 ? "file" : "files"}
                    </div>
                    <div>
                      Created: {getTimeAgo(collection.created_at)}
                    </div>
                    {collection.is_shared && (
                      <div style={{ color: "#1976d2", marginTop: "5px" }}>
                        Shared Collection
                      </div>
                    )}
                  </div>
                </div>
              </div>

              {/* Collection Tags Section */}
              <div style={{ marginTop: "20px", borderTop: "1px solid #eee", paddingTop: "15px" }}>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: "10px" }}>
                  <div style={{ color: "#666", fontSize: "12px", fontWeight: "600", textTransform: "uppercase" }}>Tags</div>
                  <button
                    onClick={handleOpenCollectionTagEditor}
                    style={{
                      background: "none",
                      border: "1px solid #ddd",
                      borderRadius: "4px",
                      padding: "4px 12px",
                      fontSize: "12px",
                      cursor: "pointer",
                      color: "#666",
                    }}
                  >
                    Edit Tags
                  </button>
                </div>
                <div style={{ display: "flex", flexWrap: "wrap", gap: "8px" }}>
                  {collection.tags && collection.tags.length > 0 ? (
                    collection.tags.map((tag) => (
                      <span
                        key={tag.id}
                        style={{
                          display: "inline-flex",
                          alignItems: "center",
                          gap: "6px",
                          padding: "4px 10px",
                          borderRadius: "12px",
                          fontSize: "12px",
                          backgroundColor: tag.color ? `${tag.color}20` : "#e0e0e0",
                          color: tag.color || "#666",
                          border: `1px solid ${tag.color || "#ccc"}`,
                        }}
                      >
                        <span
                          style={{
                            width: "8px",
                            height: "8px",
                            borderRadius: "50%",
                            backgroundColor: tag.color || "#888",
                          }}
                        />
                        {tag.name}
                        <button
                          onClick={() => handleRemoveCollectionTag(tag.id)}
                          style={{
                            background: "none",
                            border: "none",
                            cursor: "pointer",
                            padding: "0 2px",
                            color: tag.color || "#666",
                            fontSize: "14px",
                            lineHeight: "1",
                            opacity: 0.7,
                          }}
                          title="Remove tag"
                        >
                          ×
                        </button>
                      </span>
                    ))
                  ) : (
                    <span style={{ color: "#999", fontSize: "13px", fontStyle: "italic" }}>No tags assigned</span>
                  )}
                </div>
              </div>
            </div>
          )}

          {/* Search Bar and Tag Filter */}
          <div style={{ marginBottom: "20px" }}>
            <div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
              <input
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder="Search files and folders..."
                style={{
                  flex: 1,
                  minWidth: "200px",
                  padding: "10px 12px",
                  border: "1px solid #ddd",
                  borderRadius: "4px",
                  fontSize: "14px",
                  color: "#333",
                }}
              />
              {allTags.length > 0 && (
                <button
                  onClick={() => setShowTagFilter(!showTagFilter)}
                  className="nav-button"
                  style={{
                    padding: "10px 16px",
                    background: selectedTagIds.length > 0 ? "#1976d2" : "white",
                    color: selectedTagIds.length > 0 ? "white" : "#333",
                  }}
                >
                  🏷️ Tags {selectedTagIds.length > 0 && `(${selectedTagIds.length})`}
                </button>
              )}
            </div>

            {/* Tag Filter Panel */}
            {showTagFilter && allTags.length > 0 && (
              <div
                style={{
                  padding: "15px",
                  background: "#f9f9f9",
                  border: "1px solid #ddd",
                  borderRadius: "4px",
                  marginTop: "10px",
                }}
              >
                <div
                  style={{
                    display: "flex",
                    justifyContent: "space-between",
                    alignItems: "center",
                    marginBottom: "10px",
                  }}
                >
                  <strong>Filter by Tags</strong>
                  {selectedTagIds.length > 0 && (
                    <button
                      onClick={() => setSelectedTagIds([])}
                      style={{
                        background: "none",
                        border: "none",
                        color: "#1976d2",
                        cursor: "pointer",
                        fontSize: "12px",
                        textDecoration: "underline",
                      }}
                    >
                      Clear all
                    </button>
                  )}
                </div>
                <div
                  style={{
                    display: "flex",
                    flexWrap: "wrap",
                    gap: "8px",
                  }}
                >
                  {allTags.map((tag) => {
                    const isSelected = selectedTagIds.includes(tag.id);
                    return (
                      <button
                        key={tag.id}
                        onClick={() => {
                          if (isSelected) {
                            setSelectedTagIds(selectedTagIds.filter((id) => id !== tag.id));
                          } else {
                            setSelectedTagIds([...selectedTagIds, tag.id]);
                          }
                        }}
                        style={{
                          display: "inline-flex",
                          alignItems: "center",
                          gap: "6px",
                          padding: "6px 12px",
                          borderRadius: "16px",
                          fontSize: "13px",
                          backgroundColor: isSelected
                            ? tag.color || "#666"
                            : "white",
                          color: isSelected ? "white" : tag.color || "#666",
                          border: `2px solid ${tag.color || "#666"}`,
                          cursor: "pointer",
                          transition: "all 0.2s ease",
                        }}
                      >
                        <span
                          style={{
                            display: "inline-block",
                            width: "8px",
                            height: "8px",
                            borderRadius: "50%",
                            backgroundColor: isSelected ? "white" : tag.color || "#666",
                          }}
                        />
                        {tag.name}
                      </button>
                    );
                  })}
                </div>
                <div
                  style={{
                    fontSize: "12px",
                    color: "#666",
                    marginTop: "10px",
                  }}
                >
                  {selectedTagIds.length === 0
                    ? "Select one or more tags to filter files"
                    : `Showing files with ${selectedTagIds.length === 1 ? "this tag" : "all selected tags"}`}
                </div>
              </div>
            )}
          </div>

          {/* Quick Actions */}
          <div style={{ marginBottom: "30px" }}>
            <h3 style={{ color: "#333" }}>Quick Actions</h3>
            <div className="nav-buttons">
              <button
                onClick={handleCreateSubCollection}
                className="nav-button success"
              >
                + Create Sub-Collection
              </button>
              <button
                onClick={handleUploadFile}
                className="nav-button success"
              >
                ↑ Upload File
              </button>
              <button
                onClick={() => navigate(`/file-manager/collections/${collectionId}/share`)}
                className="nav-button"
              >
                Share Collection
              </button>
              <button
                onClick={() => navigate(`/file-manager/collections/${collectionId}/edit`)}
                className="nav-button secondary"
              >
                Edit Collection
              </button>
            </div>
          </div>

          {/* Sub-Collections Section */}
          {filteredSubCollections.length > 0 && (
            <div style={{ marginBottom: "30px" }}>
              <h3 style={{ color: "#333" }}>
                Sub-Collections ({filteredSubCollections.length})
              </h3>
              <div className="dashboard-grid">
                {filteredSubCollections.map((subCol) => (
                  <div
                    key={subCol.id}
                    className="dashboard-card"
                    style={{ cursor: "pointer" }}
                    onClick={() => navigate(`/file-manager/collections/${subCol.id}`)}
                  >
                    <div style={{ fontSize: "48px", marginBottom: "10px" }}>
                      {subCol.custom_icon
                        ? subCol.custom_icon
                        : subCol.is_shared
                          ? "🔗"
                          : "📁"}
                    </div>
                    <h3 style={{ marginBottom: "5px", color: "#333" }}>
                      {subCol.name || "Unnamed Collection"}
                    </h3>
                    {subCol.description && (
                      <p style={{ fontSize: "12px", color: "#666", marginBottom: "10px" }}>
                        {subCol.description}
                      </p>
                    )}
                    <div
                      style={{
                        fontSize: "14px",
                        color: "#666",
                        marginTop: "10px",
                        paddingTop: "10px",
                        borderTop: "1px solid #eee",
                      }}
                    >
                      <div>
                        {subCol.file_count || 0}{" "}
                        {subCol.file_count === 1 ? "file" : "files"}
                      </div>
                      {subCol.is_shared && (
                        <div
                          style={{
                            fontSize: "12px",
                            color: "#1976d2",
                            marginTop: "5px",
                          }}
                        >
                          Shared
                        </div>
                      )}
                      {subCol.modified_at && (
                        <div style={{ fontSize: "12px", marginTop: "5px" }}>
                          {getTimeAgo(subCol.modified_at)}
                        </div>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Files Section */}
          {filteredFiles.length > 0 && (
            <div style={{ marginBottom: "30px" }}>
              <h3 style={{ color: "#333" }}>
                Files ({filteredFiles.length})
              </h3>
              <div
                style={{
                  background: "white",
                  borderRadius: "8px",
                  border: "1px solid #ddd",
                  overflow: "hidden",
                }}
              >
                <table style={{ width: "100%", borderCollapse: "collapse" }}>
                  <thead style={{ background: "#f5f5f5", borderBottom: "1px solid #ddd" }}>
                    <tr>
                      <th style={{ padding: "12px", textAlign: "left", fontWeight: "bold", color: "#333" }}>
                        File Name
                      </th>
                      <th style={{ padding: "12px", textAlign: "center", fontWeight: "bold", width: "80px", color: "#333" }}>
                        Status
                      </th>
                      <th style={{ padding: "12px", textAlign: "left", fontWeight: "bold", color: "#333" }}>
                        Size
                      </th>
                      <th style={{ padding: "12px", textAlign: "left", fontWeight: "bold", color: "#333" }}>
                        Modified
                      </th>
                      <th style={{ padding: "12px", textAlign: "left", fontWeight: "bold", color: "#333" }}>
                        Tags
                      </th>
                      <th style={{ padding: "12px", textAlign: "right", fontWeight: "bold", color: "#333" }}>
                        Actions
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    {filteredFiles.map((file) => {
                      const syncInfo = getSyncStatusInfo(file.sync_status);
                      const isLoading = loadingFileId === file.id;

                      return (
                        <tr
                          key={file.id}
                          style={{
                            borderBottom: "1px solid #eee",
                            cursor: "pointer",
                            opacity: isLoading ? 0.7 : 1,
                          }}
                          onClick={() => navigate(`/file-manager/files/${file.id}`)}
                        >
                          <td style={{ padding: "12px" }}>
                            <div style={{ display: "flex", alignItems: "center", gap: "10px" }}>
                              <span style={{ fontSize: "24px" }}>📄</span>
                              <span style={{ color: "#333" }}>{file.filename}</span>
                            </div>
                          </td>
                          <td style={{ padding: "12px", textAlign: "center" }}>
                            <span
                              title={syncInfo.tooltip}
                              style={{
                                display: "inline-flex",
                                alignItems: "center",
                                justifyContent: "center",
                                padding: "4px 8px",
                                borderRadius: "12px",
                                fontSize: "14px",
                                backgroundColor: `${syncInfo.color}20`,
                                color: syncInfo.color,
                                fontWeight: "500",
                                cursor: "help",
                              }}
                            >
                              {syncInfo.icon}
                            </span>
                          </td>
                          <td style={{ padding: "12px", color: "#666" }}>
                            {formatFileSize(file.size)}
                          </td>
                          <td style={{ padding: "12px", color: "#666" }}>
                            {getTimeAgo(file.modified_at)}
                          </td>
                          <td style={{ padding: "12px" }}>
                            <div style={{ display: "flex", flexWrap: "wrap", gap: "4px" }}>
                              {file.tags && file.tags.length > 0 ? (
                                file.tags.slice(0, 3).map((tag) => (
                                  <span
                                    key={tag.id}
                                    style={{
                                      display: "inline-block",
                                      padding: "2px 8px",
                                      borderRadius: "12px",
                                      fontSize: "11px",
                                      backgroundColor: tag.color ? `${tag.color}20` : "#e3f2fd",
                                      color: tag.color || "#1976d2",
                                      fontWeight: "500",
                                      whiteSpace: "nowrap",
                                    }}
                                  >
                                    {tag.name}
                                  </span>
                                ))
                              ) : (
                                <span style={{ color: "#ccc", fontSize: "11px" }}>-</span>
                              )}
                              {file.tags && file.tags.length > 3 && (
                                <span style={{ color: "#999", fontSize: "11px" }}>
                                  +{file.tags.length - 3}
                                </span>
                              )}
                            </div>
                          </td>
                          <td style={{ padding: "12px", textAlign: "right" }}>
                            <div style={{ display: "flex", gap: "8px", justifyContent: "flex-end" }}>
                              {/* Show different actions based on sync status */}
                              {file.sync_status === "cloud_only" && (
                                <button
                                  onClick={(e) => handleOnloadFile(e, file.id)}
                                  disabled={isLoading}
                                  className="nav-button success"
                                  style={{ fontSize: "12px", padding: "6px 12px" }}
                                  title="Download from cloud for offline access"
                                >
                                  {isLoading ? "..." : "☁️⬇️ Onload"}
                                </button>
                              )}
                              {(file.sync_status === "synced" || file.has_local_content) && (
                                <>
                                  <button
                                    onClick={(e) => handleOpenFile(e, file.id)}
                                    className="nav-button"
                                    style={{ fontSize: "12px", padding: "6px 12px" }}
                                    title="Open file with default application"
                                  >
                                    📂 Open
                                  </button>
                                  <button
                                    onClick={(e) => handleOffloadFile(e, file.id)}
                                    disabled={isLoading}
                                    className="nav-button secondary"
                                    style={{ fontSize: "12px", padding: "6px 12px" }}
                                    title="Remove local copy, keep in cloud only"
                                  >
                                    {isLoading ? "..." : "☁️⬆️ Offload"}
                                  </button>
                                </>
                              )}
                              {file.sync_status === "modified_locally" && (
                                <button
                                  onClick={(e) => {
                                    e.stopPropagation();
                                    // TODO: Push changes to cloud
                                    console.log("Pushing changes for:", file.id);
                                  }}
                                  disabled={isLoading}
                                  className="nav-button success"
                                  style={{ fontSize: "12px", padding: "6px 12px" }}
                                  title="Push local changes to cloud"
                                >
                                  {isLoading ? "..." : "⬆️ Push"}
                                </button>
                              )}
                              <button
                                onClick={(e) => handleDownloadFile(e, file.id)}
                                disabled={isLoading}
                                className="nav-button secondary"
                                style={{ fontSize: "12px", padding: "6px 12px" }}
                                title="Save to a specific location"
                              >
                                {isLoading ? "..." : "💾 Save As"}
                              </button>
                            </div>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            </div>
          )}

          {/* Empty State */}
          {filteredSubCollections.length === 0 && filteredFiles.length === 0 && (
            <div
              style={{
                textAlign: "center",
                padding: "60px 20px",
                background: "#f5f5f5",
                borderRadius: "8px",
              }}
            >
              <div style={{ fontSize: "64px", marginBottom: "15px" }}>
                {searchQuery ? "🔍" : "📁"}
              </div>
              <h3 style={{ marginBottom: "10px", color: "#333" }}>
                {searchQuery ? "No items found" : "This collection is empty"}
              </h3>
              <p style={{ color: "#666", marginBottom: "20px" }}>
                {searchQuery
                  ? `No items match "${searchQuery}"`
                  : "Create sub-collections or upload files to get started"}
              </p>
              {!searchQuery && (
                <div className="nav-buttons" style={{ justifyContent: "center" }}>
                  <button
                    onClick={handleCreateSubCollection}
                    className="nav-button success"
                  >
                    + Create Sub-Collection
                  </button>
                  <button
                    onClick={handleUploadFile}
                    className="nav-button success"
                  >
                    ↑ Upload File
                  </button>
                </div>
              )}
            </div>
          )}

          {/* Collection Tag Editor Modal */}
          {showCollectionTagEditor && (
            <div
              style={{
                position: "fixed",
                top: 0,
                left: 0,
                right: 0,
                bottom: 0,
                background: "rgba(0, 0, 0, 0.5)",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                zIndex: 1000,
              }}
              onClick={() => !isSavingCollectionTags && setShowCollectionTagEditor(false)}
            >
              <div
                style={{
                  background: "white",
                  padding: "30px",
                  borderRadius: "8px",
                  maxWidth: "400px",
                  width: "90%",
                  boxShadow: "0 4px 20px rgba(0, 0, 0, 0.3)",
                }}
                onClick={(e) => e.stopPropagation()}
              >
                <h3 style={{ margin: "0 0 20px 0", color: "#333" }}>Edit Collection Tags</h3>

                {collectionTagError && (
                  <div
                    style={{
                      padding: "10px 15px",
                      background: "#ffebee",
                      color: "#c62828",
                      borderRadius: "4px",
                      marginBottom: "15px",
                      fontSize: "13px",
                    }}
                  >
                    {collectionTagError}
                  </div>
                )}

                {allTags.length === 0 ? (
                  <div style={{ textAlign: "center", padding: "30px", color: "#666" }}>
                    <p style={{ margin: "0 0 10px 0" }}>No tags available.</p>
                    <p style={{ margin: 0, fontSize: "13px" }}>
                      Create tags in the Tags section first.
                    </p>
                  </div>
                ) : (
                  <div style={{ maxHeight: "300px", overflowY: "auto", marginBottom: "20px" }}>
                    {allTags.map((tag) => (
                      <label
                        key={tag.id}
                        style={{
                          display: "flex",
                          alignItems: "center",
                          gap: "12px",
                          padding: "12px",
                          cursor: "pointer",
                          borderRadius: "6px",
                          backgroundColor: selectedCollectionTagIds.includes(tag.id) ? "#e3f2fd" : "transparent",
                          marginBottom: "4px",
                          transition: "background-color 0.15s",
                        }}
                      >
                        <input
                          type="checkbox"
                          checked={selectedCollectionTagIds.includes(tag.id)}
                          onChange={() => handleToggleCollectionTag(tag.id)}
                          style={{ width: "18px", height: "18px", cursor: "pointer" }}
                        />
                        <span
                          style={{
                            width: "14px",
                            height: "14px",
                            borderRadius: "50%",
                            backgroundColor: tag.color || "#888",
                            flexShrink: 0,
                          }}
                        />
                        <span style={{ color: "#333", fontSize: "14px" }}>{tag.name}</span>
                      </label>
                    ))}
                  </div>
                )}

                <div style={{ display: "flex", gap: "10px", justifyContent: "flex-end" }}>
                  <button
                    onClick={() => setShowCollectionTagEditor(false)}
                    disabled={isSavingCollectionTags}
                    style={{
                      padding: "10px 20px",
                      border: "1px solid #ddd",
                      borderRadius: "5px",
                      backgroundColor: "#f5f5f5",
                      color: "#333",
                      cursor: isSavingCollectionTags ? "not-allowed" : "pointer",
                      fontSize: "14px",
                    }}
                  >
                    Cancel
                  </button>
                  <button
                    onClick={handleSaveCollectionTags}
                    disabled={isSavingCollectionTags}
                    style={{
                      padding: "10px 20px",
                      border: "none",
                      borderRadius: "5px",
                      backgroundColor: "#3b82f6",
                      color: "white",
                      cursor: isSavingCollectionTags ? "not-allowed" : "pointer",
                      fontSize: "14px",
                      opacity: isSavingCollectionTags ? 0.7 : 1,
                    }}
                  >
                    {isSavingCollectionTags ? "Saving..." : "Save Tags"}
                  </button>
                </div>
              </div>
            </div>
          )}

          {/* Delete Confirmation Modal */}
          {showDeleteConfirm && (
            <div
              style={{
                position: "fixed",
                top: 0,
                left: 0,
                right: 0,
                bottom: 0,
                backgroundColor: "rgba(0, 0, 0, 0.5)",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                zIndex: 1000,
              }}
              onClick={() => !isDeleting && setShowDeleteConfirm(false)}
            >
              <div
                style={{
                  backgroundColor: "white",
                  borderRadius: "8px",
                  padding: "30px",
                  maxWidth: "500px",
                  width: "90%",
                  boxShadow: "0 4px 6px rgba(0, 0, 0, 0.1)",
                }}
                onClick={(e) => e.stopPropagation()}
              >
                <h2 style={{ marginBottom: "15px", color: "#d32f2f" }}>
                  ⚠️ Delete Collection?
                </h2>
                <p style={{ marginBottom: "10px", color: "#333" }}>
                  Are you sure you want to delete <strong>{collection?.name}</strong>?
                </p>
                <p style={{ marginBottom: "20px", color: "#666", fontSize: "14px" }}>
                  This will permanently delete:
                </p>
                <ul style={{ marginBottom: "20px", color: "#666", fontSize: "14px", paddingLeft: "20px" }}>
                  <li>The collection and all its contents</li>
                  <li>All files in this collection ({collection?.file_count || 0} files)</li>
                  {subCollections.length > 0 && (
                    <li>All sub-collections ({subCollections.length} sub-collections)</li>
                  )}
                </ul>
                <p style={{ marginBottom: "20px", color: "#d32f2f", fontSize: "14px", fontWeight: "bold" }}>
                  This action cannot be undone!
                </p>

                <div style={{ display: "flex", gap: "10px", justifyContent: "flex-end" }}>
                  <button
                    onClick={() => setShowDeleteConfirm(false)}
                    disabled={isDeleting}
                    style={{
                      padding: "10px 20px",
                      border: "1px solid #ddd",
                      borderRadius: "5px",
                      backgroundColor: "#f5f5f5",
                      color: "#333",
                      cursor: isDeleting ? "not-allowed" : "pointer",
                      fontSize: "14px",
                    }}
                  >
                    Cancel
                  </button>
                  <button
                    onClick={handleDeleteCollection}
                    disabled={isDeleting}
                    style={{
                      padding: "10px 20px",
                      border: "none",
                      borderRadius: "5px",
                      backgroundColor: "#d32f2f",
                      color: "white",
                      cursor: isDeleting ? "not-allowed" : "pointer",
                      fontSize: "14px",
                      opacity: isDeleting ? 0.7 : 1,
                    }}
                  >
                    {isDeleting ? "Deleting..." : "Delete Collection"}
                  </button>
                </div>
              </div>
            </div>
          )}
        </Page>
      </div>
    </div>
  );
}

export default CollectionDetails;
