// File Path: monorepo/native/desktop/maplefile/frontend/src/pages/User/Tags/TagSearch.jsx
import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import Navigation from "../../../components/Navigation";
import Page from "../../../components/Page";

function TagSearch() {
  const navigate = useNavigate();
  const [availableTags, setAvailableTags] = useState([]);
  const [selectedTagIds, setSelectedTagIds] = useState([]);
  const [searchResults, setSearchResults] = useState(null);
  const [decryptedCollections, setDecryptedCollections] = useState([]);
  const [decryptedFiles, setDecryptedFiles] = useState([]);
  const [isLoadingTags, setIsLoadingTags] = useState(true);
  const [isSearching, setIsSearching] = useState(false);
  const [isDecrypting, setIsDecrypting] = useState(false);
  const [error, setError] = useState("");

  const loadTags = async () => {
    try {
      setIsLoadingTags(true);
      setError("");
      const { ListTags } = await import("../../../../wailsjs/go/app/Application");
      const fetchedTags = await ListTags();
      setAvailableTags(fetchedTags || []);
    } catch (err) {
      console.error("Failed to load tags:", err);
      setError(err.message || "Failed to load tags");
    } finally {
      setIsLoadingTags(false);
    }
  };

  useEffect(() => {
    // Wait for Wails runtime to be ready before loading data
    let attempts = 0;
    const maxAttempts = 50; // 5 seconds max (50 * 100ms)
    let isCancelled = false; // Prevent race conditions

    const checkWailsReady = () => {
      if (isCancelled) return;

      if (window.go && window.go.app && window.go.app.Application) {
        loadTags();
      } else if (attempts < maxAttempts) {
        attempts++;
        setTimeout(checkWailsReady, 100);
      } else {
        // Timeout - show error
        if (!isCancelled) {
          setError("Failed to initialize application. Please reload.");
          setIsLoadingTags(false);
        }
      }
    };

    checkWailsReady();

    // Cleanup function to prevent race conditions with StrictMode
    return () => {
      isCancelled = true;
    };
  }, []);

  const handleTagToggle = (tagId) => {
    if (selectedTagIds.includes(tagId)) {
      setSelectedTagIds(selectedTagIds.filter((id) => id !== tagId));
    } else {
      setSelectedTagIds([...selectedTagIds, tagId]);
    }
  };

  const handleSearch = async () => {
    if (selectedTagIds.length === 0) {
      setError("Please select at least one tag");
      return;
    }

    try {
      setIsSearching(true);
      setError("");
      setDecryptedCollections([]);
      setDecryptedFiles([]);

      const { SearchByTags, GetCollection, GetFile } = await import("../../../../wailsjs/go/app/Application");
      const results = await SearchByTags(selectedTagIds, 50); // Limit to 50 results
      setSearchResults(results);

      // Fetch and decrypt collection details
      if (results.collection_ids && results.collection_ids.length > 0) {
        setIsDecrypting(true);
        const collectionPromises = results.collection_ids.map(async (id) => {
          try {
            return await GetCollection(id);
          } catch (error) {
            console.error("Failed to fetch collection:", id, error);
            return null;
          }
        });
        const collections = (await Promise.all(collectionPromises)).filter(Boolean);
        setDecryptedCollections(collections);
      }

      // Fetch and decrypt file details
      if (results.file_ids && results.file_ids.length > 0) {
        setIsDecrypting(true);
        const filePromises = results.file_ids.map(async (id) => {
          try {
            return await GetFile(id);
          } catch (error) {
            console.error("Failed to fetch file:", id, error);
            return null;
          }
        });
        const files = (await Promise.all(filePromises)).filter(Boolean);
        setDecryptedFiles(files);
      }
    } catch (err) {
      console.error("Failed to search by tags:", err);
      setError(err.message || "Failed to search by tags");
    } finally {
      setIsSearching(false);
      setIsDecrypting(false);
    }
  };

  const handleClearSelection = () => {
    setSelectedTagIds([]);
    setSearchResults(null);
    setDecryptedCollections([]);
    setDecryptedFiles([]);
    setError("");
  };

  const handleCollectionClick = (collectionId) => {
    navigate(`/file-manager/collections/${collectionId}`);
  };

  const handleFileClick = (fileId) => {
    navigate(`/file-manager/files/${fileId}`);
  };

  if (isLoadingTags) {
    return (
      <div className="layout">
        <Navigation />
        <div className="main-content">
          <Page title="Search by Tags">
            <div style={{ padding: "20px", textAlign: "center" }}>
              <p>Loading tags...</p>
            </div>
          </Page>
        </div>
      </div>
    );
  }

  if (error && !searchResults) {
    return (
      <div className="layout">
        <Navigation />
        <div className="main-content">
          <Page title="Search by Tags">
            <div style={{ padding: "20px", textAlign: "center" }}>
              <p style={{ color: "#d32f2f" }}>{error}</p>
              <button
                onClick={loadTags}
                style={{
                  marginTop: "10px",
                  padding: "8px 16px",
                  background: "#1976d2",
                  color: "white",
                  border: "none",
                  borderRadius: "4px",
                  cursor: "pointer",
                }}
              >
                Retry
              </button>
            </div>
          </Page>
        </div>
      </div>
    );
  }

  return (
    <div className="layout">
      <Navigation />
      <div className="main-content">
        <Page title="Search by Tags">
          <div style={{ padding: "20px" }}>
            {/* Header */}
            <div
              style={{
                display: "flex",
                justifyContent: "space-between",
                alignItems: "center",
                marginBottom: "20px",
              }}
            >
              <h1 style={{ margin: 0 }}>Search by Tags</h1>
              <button
                onClick={() => navigate("/tags")}
                className="nav-button"
                style={{ padding: "8px 16px" }}
              >
                ← Back to Tags
              </button>
            </div>

      {/* Tag Selection */}
      <div
        style={{
          background: "#f5f5f5",
          padding: "15px",
          borderRadius: "4px",
          marginBottom: "20px",
        }}
      >
        <h3 style={{ marginTop: 0 }}>
          Select Tags ({selectedTagIds.length} selected)
        </h3>
        {availableTags.length === 0 ? (
          <p>No tags available. Create tags first to use search.</p>
        ) : (
          <div
            style={{
              display: "flex",
              flexWrap: "wrap",
              gap: "10px",
              marginBottom: "15px",
            }}
          >
            {availableTags.map((tag) => {
              const isSelected = selectedTagIds.includes(tag.id);
              return (
                <button
                  key={tag.id}
                  onClick={() => handleTagToggle(tag.id)}
                  style={{
                    padding: "8px 16px",
                    border: `2px solid ${tag.color || "#666"}`,
                    borderRadius: "16px",
                    background: isSelected ? tag.color || "#666" : "white",
                    color: isSelected ? "white" : tag.color || "#666",
                    cursor: "pointer",
                    fontWeight: "500",
                    transition: "all 0.2s",
                    display: "flex",
                    alignItems: "center",
                    gap: "6px",
                  }}
                >
                  <span
                    style={{
                      display: "inline-block",
                      width: "12px",
                      height: "12px",
                      borderRadius: "50%",
                      background: isSelected ? "white" : tag.color || "#666",
                    }}
                  />
                  {tag.name}
                </button>
              );
            })}
          </div>
        )}

        <div style={{ display: "flex", gap: "10px" }}>
          <button
            onClick={handleSearch}
            disabled={selectedTagIds.length === 0 || isSearching}
            style={{
              padding: "10px 20px",
              background:
                selectedTagIds.length === 0 || isSearching
                  ? "#ccc"
                  : "#1976d2",
              color: "white",
              border: "none",
              borderRadius: "4px",
              cursor:
                selectedTagIds.length === 0 || isSearching
                  ? "not-allowed"
                  : "pointer",
              fontWeight: "500",
            }}
          >
            {isSearching ? "Searching..." : "Search"}
          </button>
          {selectedTagIds.length > 0 && (
            <button
              onClick={handleClearSelection}
              style={{
                padding: "10px 20px",
                background: "white",
                color: "#666",
                border: "1px solid #ccc",
                borderRadius: "4px",
                cursor: "pointer",
              }}
            >
              Clear Selection
            </button>
          )}
        </div>
      </div>

      {/* Search Results */}
      {searchResults && (
        <div>
          <h2 style={{ marginBottom: "15px" }}>
            Search Results - {searchResults.collection_count} Collections,{" "}
            {searchResults.file_count} Files
          </h2>

          {searchResults.collection_count === 0 &&
            searchResults.file_count === 0 && (
              <div
                style={{
                  padding: "40px",
                  textAlign: "center",
                  background: "#f9f9f9",
                  borderRadius: "4px",
                }}
              >
                <p style={{ fontSize: "16px", color: "#666" }}>
                  No collections or files found with the selected tags.
                </p>
              </div>
            )}

          {/* Decrypting Indicator */}
          {isDecrypting && (
            <div
              style={{
                padding: "20px",
                textAlign: "center",
                background: "#f9f9f9",
                borderRadius: "4px",
                marginBottom: "20px",
              }}
            >
              <p style={{ fontSize: "14px", color: "#666" }}>
                Decrypting results...
              </p>
            </div>
          )}

          {/* Collections Section */}
          {decryptedCollections.length > 0 && (
              <div style={{ marginBottom: "30px" }}>
                <h3 style={{ marginBottom: "10px" }}>
                  Collections ({decryptedCollections.length})
                </h3>
                <div style={{ display: "flex", flexDirection: "column", gap: "10px" }}>
                  {decryptedCollections.map((collection) => (
                    <div
                      key={collection.id}
                      onClick={() => handleCollectionClick(collection.id)}
                      style={{
                        padding: "15px",
                        background: "white",
                        border: "1px solid #ddd",
                        borderRadius: "4px",
                        cursor: "pointer",
                        transition: "all 0.2s",
                      }}
                      onMouseEnter={(e) => {
                        e.currentTarget.style.background = "#f5f5f5";
                        e.currentTarget.style.borderColor = "#1976d2";
                      }}
                      onMouseLeave={(e) => {
                        e.currentTarget.style.background = "white";
                        e.currentTarget.style.borderColor = "#ddd";
                      }}
                    >
                      <div
                        style={{
                          display: "flex",
                          alignItems: "center",
                          gap: "10px",
                        }}
                      >
                        <span style={{ fontSize: "24px" }}>📁</span>
                        <div style={{ flex: 1 }}>
                          <div style={{ fontWeight: "600", fontSize: "15px", color: "#333", marginBottom: "4px" }}>
                            {collection.name}
                          </div>
                          {collection.description && (
                            <div style={{ fontSize: "13px", color: "#666", marginBottom: "4px" }}>
                              {collection.description}
                            </div>
                          )}
                          <div style={{ fontSize: "12px", color: "#999" }}>
                            {collection.file_count || 0} files • Created {new Date(collection.created_at).toLocaleDateString()}
                          </div>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}

          {/* Files Section */}
          {decryptedFiles.length > 0 && (
            <div>
              <h3 style={{ marginBottom: "10px" }}>
                Files ({decryptedFiles.length})
              </h3>
              <div style={{ display: "flex", flexDirection: "column", gap: "10px" }}>
                {decryptedFiles.map((file) => (
                  <div
                    key={file.id}
                    onClick={() => handleFileClick(file.id)}
                    style={{
                      padding: "15px",
                      background: "white",
                      border: "1px solid #ddd",
                      borderRadius: "4px",
                      cursor: "pointer",
                      transition: "all 0.2s",
                    }}
                    onMouseEnter={(e) => {
                      e.currentTarget.style.background = "#f5f5f5";
                      e.currentTarget.style.borderColor = "#1976d2";
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.background = "white";
                      e.currentTarget.style.borderColor = "#ddd";
                    }}
                  >
                    <div
                      style={{
                        display: "flex",
                        alignItems: "center",
                        gap: "10px",
                      }}
                    >
                      <span style={{ fontSize: "24px" }}>📄</span>
                      <div style={{ flex: 1 }}>
                        <div style={{ fontWeight: "600", fontSize: "15px", color: "#333", marginBottom: "4px" }}>
                          {file.filename}
                        </div>
                        <div style={{ fontSize: "12px", color: "#999" }}>
                          {formatFileSize(file.size)} • Uploaded {new Date(file.created_at).toLocaleDateString()}
                        </div>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      )}
          </div>
        </Page>
      </div>
    </div>
  );
}

// Helper function to format file size
function formatFileSize(bytes) {
  if (bytes === 0) return "0 Bytes";
  const k = 1024;
  const sizes = ["Bytes", "KB", "MB", "GB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return Math.round(bytes / Math.pow(k, i) * 100) / 100 + " " + sizes[i];
}

export default TagSearch;
