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

// Utility function to format file sizes
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`;
};

function FullTextSearch() {
  const navigate = useNavigate();
  const [searchQuery, setSearchQuery] = useState("");
  const [searchResults, setSearchResults] = useState(null);
  const [isSearching, setIsSearching] = useState(false);
  const [error, setError] = useState("");

  const handleSearch = async (e) => {
    e.preventDefault();

    if (!searchQuery.trim()) {
      setError("Please enter a search query");
      return;
    }

    try {
      setIsSearching(true);
      setError("");
      setSearchResults(null);

      const { Search } = await import("../../../../wailsjs/go/app/Application");
      const results = await Search({
        query: searchQuery.trim(),
        limit: 50,
      });

      setSearchResults(results);

      if (results.total_files === 0 && results.total_collections === 0) {
        setError(`No results found for "${searchQuery}"`);
      }
    } catch (err) {
      console.error("Search failed:", err);
      setError(err.message || "Search failed. Please try again.");
    } finally {
      setIsSearching(false);
    }
  };

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

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

  return (
    <div className="layout">
      <Navigation />
      <div className="main-content">
        <Page title="Full-Text Search">
          {/* Search Form */}
          <div style={{ marginBottom: "30px" }}>
            <form onSubmit={handleSearch}>
              <div style={{ display: "flex", gap: "12px" }}>
                <input
                  type="text"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  placeholder="Search files and collections..."
                  style={{
                    flex: 1,
                    padding: "12px 16px",
                    border: "1px solid #ddd",
                    borderRadius: "4px",
                    fontSize: "14px",
                    color: "#333",
                  }}
                  disabled={isSearching}
                />
                <button
                  type="submit"
                  disabled={isSearching || !searchQuery.trim()}
                  className="nav-button success"
                  style={{ padding: "12px 24px" }}
                >
                  {isSearching ? "Searching..." : "🔍 Search"}
                </button>
              </div>

              {/* Search Tips */}
              <div style={{ marginTop: "10px", fontSize: "13px", color: "#666" }}>
                <p style={{ margin: 0 }}>
                  <strong>Search tips:</strong> Use quotes for exact phrases (e.g., "project report"),
                  + for AND logic, - to exclude terms
                </p>
              </div>
            </form>
          </div>

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

          {/* Search Results */}
          {searchResults && (
            <>
              {/* Results Summary */}
              <div
                style={{
                  padding: "15px 20px",
                  background: "#e3f2fd",
                  color: "#1976d2",
                  borderRadius: "4px",
                  marginBottom: "30px",
                  border: "1px solid #90caf9",
                }}
              >
                <p style={{ margin: 0, fontWeight: "500" }}>
                  Found <strong>{searchResults.total_files}</strong> file(s) and{" "}
                  <strong>{searchResults.total_collections}</strong> collection(s)
                  {searchResults.total_hits > 0 && (
                    <span> ({searchResults.total_hits} total matches)</span>
                  )}
                </p>
              </div>

              {/* Files Section */}
              {searchResults.files && searchResults.files.length > 0 && (
                <div style={{ marginBottom: "40px" }}>
                  <h3 style={{ color: "#333", marginBottom: "15px" }}>
                    Files ({searchResults.total_files})
                  </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: "left", fontWeight: "bold", color: "#333" }}>
                            Collection
                          </th>
                          <th style={{ padding: "12px", textAlign: "left", fontWeight: "bold", color: "#333" }}>
                            Size
                          </th>
                          <th style={{ padding: "12px", textAlign: "left", fontWeight: "bold", color: "#333" }}>
                            Created
                          </th>
                          <th style={{ padding: "12px", textAlign: "left", fontWeight: "bold", color: "#333" }}>
                            Tags
                          </th>
                        </tr>
                      </thead>
                      <tbody>
                        {searchResults.files.map((file) => (
                          <tr
                            key={file.id}
                            style={{
                              borderBottom: "1px solid #eee",
                              cursor: "pointer",
                            }}
                            onClick={() => handleFileClick(file.id)}
                            onMouseEnter={(e) => e.currentTarget.style.backgroundColor = "#f9f9f9"}
                            onMouseLeave={(e) => e.currentTarget.style.backgroundColor = "white"}
                          >
                            <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" }}>
                              {file.collection_name ? (
                                <div style={{ display: "flex", alignItems: "center", gap: "6px", color: "#666" }}>
                                  <svg style={{ width: "16px", height: "16px" }} 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-2h-6l-2-2H5a2 2 0 00-2 2z" />
                                  </svg>
                                  <span>{file.collection_name}</span>
                                </div>
                              ) : (
                                <span style={{ color: "#ccc" }}>-</span>
                              )}
                            </td>
                            <td style={{ padding: "12px", color: "#666" }}>
                              {formatFileSize(file.size)}
                            </td>
                            <td style={{ padding: "12px", color: "#666" }}>
                              {getTimeAgo(file.created_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, idx) => (
                                    <span
                                      key={idx}
                                      style={{
                                        display: "inline-block",
                                        padding: "2px 8px",
                                        borderRadius: "12px",
                                        fontSize: "11px",
                                        backgroundColor: "#e3f2fd",
                                        color: "#1976d2",
                                        fontWeight: "500",
                                        whiteSpace: "nowrap",
                                      }}
                                    >
                                      {tag}
                                    </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>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                </div>
              )}

              {/* Collections Section */}
              {searchResults.collections && searchResults.collections.length > 0 && (
                <div style={{ marginBottom: "40px" }}>
                  <h3 style={{ color: "#333", marginBottom: "15px" }}>
                    Collections ({searchResults.total_collections})
                  </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" }}>
                            Collection Name
                          </th>
                          <th style={{ padding: "12px", textAlign: "center", fontWeight: "bold", color: "#333" }}>
                            Files
                          </th>
                          <th style={{ padding: "12px", textAlign: "left", fontWeight: "bold", color: "#333" }}>
                            Created
                          </th>
                          <th style={{ padding: "12px", textAlign: "left", fontWeight: "bold", color: "#333" }}>
                            Tags
                          </th>
                        </tr>
                      </thead>
                      <tbody>
                        {searchResults.collections.map((collection) => (
                          <tr
                            key={collection.id}
                            style={{
                              borderBottom: "1px solid #eee",
                              cursor: "pointer",
                            }}
                            onClick={() => handleCollectionClick(collection.id)}
                            onMouseEnter={(e) => e.currentTarget.style.backgroundColor = "#f9f9f9"}
                            onMouseLeave={(e) => e.currentTarget.style.backgroundColor = "white"}
                          >
                            <td style={{ padding: "12px" }}>
                              <div style={{ display: "flex", alignItems: "center", gap: "10px" }}>
                                <span style={{ fontSize: "24px" }}>📁</span>
                                <span style={{ color: "#333" }}>{collection.name}</span>
                              </div>
                            </td>
                            <td style={{ padding: "12px", textAlign: "center", color: "#666" }}>
                              {collection.file_count}
                            </td>
                            <td style={{ padding: "12px", color: "#666" }}>
                              {getTimeAgo(collection.created_at)}
                            </td>
                            <td style={{ padding: "12px" }}>
                              <div style={{ display: "flex", flexWrap: "wrap", gap: "4px" }}>
                                {collection.tags && collection.tags.length > 0 ? (
                                  collection.tags.slice(0, 3).map((tag, idx) => (
                                    <span
                                      key={idx}
                                      style={{
                                        display: "inline-block",
                                        padding: "2px 8px",
                                        borderRadius: "12px",
                                        fontSize: "11px",
                                        backgroundColor: "#e3f2fd",
                                        color: "#1976d2",
                                        fontWeight: "500",
                                        whiteSpace: "nowrap",
                                      }}
                                    >
                                      {tag}
                                    </span>
                                  ))
                                ) : (
                                  <span style={{ color: "#ccc", fontSize: "11px" }}>-</span>
                                )}
                                {collection.tags && collection.tags.length > 3 && (
                                  <span style={{ color: "#999", fontSize: "11px" }}>
                                    +{collection.tags.length - 3}
                                  </span>
                                )}
                              </div>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                </div>
              )}
            </>
          )}

          {/* Empty State - No Search Yet */}
          {!searchResults && !error && (
            <div
              style={{
                textAlign: "center",
                padding: "60px 20px",
                background: "#f5f5f5",
                borderRadius: "8px",
              }}
            >
              <div style={{ fontSize: "64px", marginBottom: "15px" }}>
                🔍
              </div>
              <h3 style={{ marginBottom: "10px", color: "#333" }}>
                Search Your Files and Collections
              </h3>
              <p style={{ color: "#666", maxWidth: "500px", margin: "0 auto" }}>
                Enter a search query above to find files and collections. You can search by filename,
                collection name, or tags.
              </p>
            </div>
          )}
        </Page>
      </div>
    </div>
  );
}

export default FullTextSearch;
