// File Path: monorepo/native/desktop/maplefile/frontend/src/pages/User/FileManager/FileManagerIndex.jsx
import { useState, useEffect, useCallback } from "react";
import { Link, useNavigate } from "react-router-dom";
import Navigation from "../../../components/Navigation";
import Page from "../../../components/Page";
import {
  ListCollections,
  GetSyncStatus,
  TriggerSync,
  ListTags,
} from "../../../../wailsjs/go/app/Application";
import "../Dashboard/Dashboard.css";

function FileManagerIndex() {
  const navigate = useNavigate();
  const [collections, setCollections] = useState([]);
  const [syncStatus, setSyncStatus] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState("");
  const [searchQuery, setSearchQuery] = useState("");
  const [filterType, setFilterType] = useState("root"); // root, all, owned, shared
  const [availableTags, setAvailableTags] = useState([]);
  const [selectedTagIds, setSelectedTagIds] = useState([]);
  const [showTagFilter, setShowTagFilter] = useState(false);

  // Load collections from local storage (synced from backend)
  const loadCollections = useCallback(async () => {
    setIsLoading(true);
    setError("");

    try {
      console.log("🔄 Loading collections...");
      const collectionsData = await ListCollections();
      console.log("✅ Collections loaded:", collectionsData);
      console.log("📊 Collections count:", collectionsData ? collectionsData.length : 0);
      if (collectionsData && collectionsData.length > 0) {
        console.log("🔍 First collection data:", JSON.stringify(collectionsData[0], null, 2));
      }
      setCollections(collectionsData || []);
    } catch (err) {
      console.error("❌ Failed to load collections:", err);
      setError(err.message || "Failed to load collections");
    } finally {
      setIsLoading(false);
    }
  }, []);

  // Load sync status
  const loadSyncStatus = useCallback(async () => {
    try {
      const status = await GetSyncStatus();
      setSyncStatus(status);
    } catch (err) {
      console.error("Failed to load sync status:", err);
    }
  }, []);

  // Load available tags
  const loadTags = useCallback(async () => {
    try {
      const tags = await ListTags();
      setAvailableTags(tags || []);
    } catch (err) {
      console.error("Failed to load tags:", err);
    }
  }, []);

  // Handle manual sync trigger
  const handleManualSync = async () => {
    try {
      await TriggerSync();
      // Reload sync status after triggering
      setTimeout(() => {
        loadSyncStatus();
        loadCollections();
      }, 1000);
    } catch (err) {
      console.error("Failed to trigger sync:", err);
      setError(err.message || "Failed to trigger sync");
    }
  };

  // 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) {
      loadCollections();
      loadSyncStatus();
      loadTags();
    } else {
      // Wait for Wails to be ready
      const checkWails = setInterval(() => {
        if (window.go && window.go.app && window.go.app.Application) {
          clearInterval(checkWails);
          loadCollections();
          loadSyncStatus();
          loadTags();
        }
      }, 100);

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

      return () => clearInterval(checkWails);
    }
  }, [loadCollections, loadSyncStatus, loadTags]);

  // Auto-refresh sync status every 5 seconds
  useEffect(() => {
    const interval = setInterval(() => {
      if (window.go && window.go.app && window.go.app.Application) {
        loadSyncStatus();
      }
    }, 5000);
    return () => clearInterval(interval);
  }, [loadSyncStatus]);

  // Helper to check if a collection is a root collection (no parent)
  const isRootCollection = (collection) => {
    return !collection.parent_id || collection.parent_id === "00000000-0000-0000-0000-000000000000";
  };

  // Filter and search collections
  const filteredCollections = collections.filter((collection) => {
    // Apply filter type
    if (filterType === "owned" && collection.is_shared) return false;
    if (filterType === "shared" && !collection.is_shared) return false;
    if (filterType === "root" && !isRootCollection(collection)) return false; // Only show root collections

    // Apply tag filter (multi-tag filtering with AND logic)
    if (selectedTagIds.length > 0) {
      const collectionTagIds = (collection.tags || []).map(tag => tag.id);
      // Check if collection has ALL selected tags
      const hasAllTags = selectedTagIds.every(tagId => collectionTagIds.includes(tagId));
      if (!hasAllTags) return false;
    }

    // Apply search query
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      return collection.name.toLowerCase().includes(query) ||
             (collection.description && collection.description.toLowerCase().includes(query));
    }

    return true;
  });

  console.log("🔍 Filtered collections:", filteredCollections);
  console.log("📊 Total collections:", collections.length, "Filtered:", filteredCollections.length);

  // Get time ago helper
  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`;
  };

  return (
    <div className="layout">
      <Navigation />
      <div className="main-content">
        <Page title="File Manager">
          {/* Sync Status Section */}
          {syncStatus && (
            <div
              style={{
                padding: "15px",
                background: syncStatus.last_sync_success ? "#e8f5e9" : "#ffebee",
                borderRadius: "4px",
                marginBottom: "20px",
                border: `1px solid ${syncStatus.last_sync_success ? "#4caf50" : "#f44336"}`,
              }}
            >
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                <div>
                  <strong>Sync Status:</strong>{" "}
                  {syncStatus.is_syncing ? (
                    <span>⏳ Syncing...</span>
                  ) : syncStatus.last_sync_success ? (
                    <span>✓ Up to date</span>
                  ) : (
                    <span>✗ Error</span>
                  )}
                  <div style={{ fontSize: "12px", marginTop: "5px", color: "#666" }}>
                    {syncStatus.last_sync_time && (
                      <div>Last sync: {getTimeAgo(syncStatus.last_sync_time)}</div>
                    )}
                    {syncStatus.collections_synced > 0 && (
                      <div>
                        Collections: {syncStatus.collections_synced}, Files: {syncStatus.files_synced}
                      </div>
                    )}
                    {syncStatus.last_sync_error && (
                      <div style={{ color: "#f44336", marginTop: "5px" }}>
                        Error: {syncStatus.last_sync_error}
                      </div>
                    )}
                  </div>
                </div>
                <button
                  onClick={handleManualSync}
                  disabled={syncStatus.is_syncing}
                  className="nav-button"
                  style={{ margin: 0 }}
                >
                  {syncStatus.is_syncing ? "Syncing..." : "Sync Now"}
                </button>
              </div>
            </div>
          )}

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

          {/* Search and Filter Bar */}
          <div style={{ marginBottom: "20px" }}>
            <div style={{ display: "flex", gap: "10px", marginBottom: "10px" }}>
              <input
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder="Search collections..."
                style={{
                  flex: 1,
                  padding: "8px 12px",
                  border: "1px solid #ddd",
                  borderRadius: "4px",
                }}
              />
              <select
                value={filterType}
                onChange={(e) => setFilterType(e.target.value)}
                style={{
                  padding: "8px 12px",
                  border: "1px solid #ddd",
                  borderRadius: "4px",
                  background: "white",
                }}
              >
                <option value="all">All Collections</option>
                <option value="root">Root Collections</option>
                <option value="owned">My Collections</option>
                <option value="shared">Shared with Me</option>
              </select>
              {availableTags.length > 0 && (
                <button
                  onClick={() => setShowTagFilter(!showTagFilter)}
                  className="nav-button"
                  style={{
                    padding: "8px 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 && availableTags.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",
                  }}
                >
                  {availableTags.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 collections"
                    : `Showing collections with ${selectedTagIds.length === 1 ? "this tag" : "all selected tags"}`}
                </div>
              </div>
            )}
          </div>

          {/* Quick Actions */}
          <div style={{ marginBottom: "30px" }}>
            <h3>Quick Actions</h3>
            <div className="nav-buttons">
              <Link
                to="/file-manager/collections/create"
                className="nav-button success"
              >
                + Create Collection
              </Link>
              <Link to="/file-manager/upload" className="nav-button success">
                ↑ Upload File
              </Link>
            </div>
          </div>

          {/* Collections Grid */}
          <h3>
            {filterType === "all" && "All Collections"}
            {filterType === "root" && "Root Collections"}
            {filterType === "owned" && "My Collections"}
            {filterType === "shared" && "Shared with Me"}
            {searchQuery && ` (${filteredCollections.length} results)`}
          </h3>

          {isLoading ? (
            <div style={{ textAlign: "center", padding: "40px" }}>
              <div>Loading collections...</div>
            </div>
          ) : filteredCollections.length === 0 ? (
            <div
              style={{
                textAlign: "center",
                padding: "40px",
                background: "#f5f5f5",
                borderRadius: "8px",
              }}
            >
              <div style={{ fontSize: "48px", marginBottom: "10px" }}>📁</div>
              <h4>
                {searchQuery
                  ? "No collections found"
                  : filterType === "shared"
                    ? "No shared collections"
                    : "No collections yet"}
              </h4>
              <p style={{ color: "#666" }}>
                {searchQuery
                  ? `No collections match "${searchQuery}"`
                  : filterType === "shared"
                    ? "When someone shares a collection with you, it will appear here"
                    : "Create your first collection to start organizing your files"}
              </p>
              {!searchQuery && filterType !== "shared" && (
                <Link
                  to="/file-manager/collections/create"
                  className="nav-button success"
                  style={{ marginTop: "20px", display: "inline-block" }}
                >
                  + Create Your First Collection
                </Link>
              )}
            </div>
          ) : (
            <div className="dashboard-grid">
              {filteredCollections.map((collection) => (
                <div
                  key={collection.id}
                  className="dashboard-card"
                  style={{ cursor: "pointer", position: "relative" }}
                  onClick={() => navigate(`/file-manager/collections/${collection.id}`)}
                >
                  {/* Collection Icon */}
                  <div
                    style={{
                      fontSize: "48px",
                      marginBottom: "10px",
                    }}
                  >
                    {collection.custom_icon
                      ? collection.custom_icon
                      : collection.is_shared
                        ? "🔗"
                        : collection.collection_type === "album"
                          ? "🖼️"
                          : "📁"}
                  </div>

                  {/* Collection Name */}
                  <h3 style={{ marginBottom: "5px", color: "#333" }}>
                    {collection.name || "Unnamed Collection"}
                  </h3>

                  {/* Collection Description */}
                  {collection.description && (
                    <p
                      style={{
                        fontSize: "12px",
                        color: "#666",
                        marginBottom: "10px",
                      }}
                    >
                      {collection.description}
                    </p>
                  )}

                  {/* Collection Stats */}
                  <div
                    style={{
                      fontSize: "14px",
                      color: "#666",
                      marginTop: "10px",
                      paddingTop: "10px",
                      borderTop: "1px solid #eee",
                    }}
                  >
                    <div>
                      {collection.file_count || 0}{" "}
                      {collection.file_count === 1 ? "file" : "files"}
                    </div>
                    {/* Collection type badge */}
                    <div
                      style={{
                        fontSize: "11px",
                        color: "#888",
                        marginTop: "5px",
                        textTransform: "capitalize",
                      }}
                    >
                      {collection.collection_type || "folder"}
                    </div>
                    {collection.is_shared && (
                      <div
                        style={{
                          fontSize: "12px",
                          color: "#1976d2",
                          marginTop: "5px",
                        }}
                      >
                        Shared
                      </div>
                    )}
                    {!isRootCollection(collection) && (
                      <div
                        style={{
                          fontSize: "11px",
                          color: "#9c27b0",
                          marginTop: "5px",
                        }}
                      >
                        Sub-collection
                      </div>
                    )}
                    {collection.modified_at && (
                      <div style={{ fontSize: "12px", marginTop: "5px" }}>
                        {getTimeAgo(collection.modified_at)}
                      </div>
                    )}
                  </div>

                  {/* Tags */}
                  {collection.tags && collection.tags.length > 0 && (
                    <div
                      style={{
                        marginTop: "10px",
                        paddingTop: "10px",
                        borderTop: "1px solid #eee",
                        display: "flex",
                        flexWrap: "wrap",
                        gap: "5px",
                      }}
                    >
                      {collection.tags.slice(0, 3).map((tag) => (
                        <span
                          key={tag.id}
                          style={{
                            display: "inline-flex",
                            alignItems: "center",
                            gap: "4px",
                            padding: "2px 8px",
                            borderRadius: "12px",
                            fontSize: "11px",
                            backgroundColor: tag.color ? `${tag.color}20` : "#e0e0e0",
                            color: tag.color || "#666",
                            border: `1px solid ${tag.color || "#ccc"}`,
                          }}
                        >
                          <span
                            style={{
                              display: "inline-block",
                              width: "6px",
                              height: "6px",
                              borderRadius: "50%",
                              backgroundColor: tag.color || "#666",
                            }}
                          />
                          {tag.name}
                        </span>
                      ))}
                      {collection.tags.length > 3 && (
                        <span
                          style={{
                            fontSize: "11px",
                            color: "#666",
                            padding: "2px 8px",
                          }}
                        >
                          +{collection.tags.length - 3} more
                        </span>
                      )}
                    </div>
                  )}
                </div>
              ))}
            </div>
          )}
        </Page>
      </div>
    </div>
  );
}

export default FileManagerIndex;
