// File: src/pages/User/Tags/TagSearchResults.jsx
// Tag Search Results Page - Display collections and files matching selected tags
// Layout pattern matching TagSearch.jsx

import React, { useState, useEffect, useCallback, useRef, useMemo } from "react";
import { useNavigate, useLocation } from "react-router";
import { useTags, useCrypto } from "../../../services/Services.jsx";
import withPasswordProtection from "../../../hocs/withPasswordProtection";
import Layout from "../../../components/Layout/Layout";
import {
  Button,
  Alert,
  Card,
  Breadcrumb,
  Spinner,
  useUIXTheme,
} from "../../../components/UIX";
import {
  MagnifyingGlassIcon,
  FolderIcon,
  DocumentIcon,
  ArrowLeftIcon,
  TagIcon,
  Cog6ToothIcon,
  InformationCircleIcon,
} from "@heroicons/react/24/outline";

// Module-level cache for FileCryptoService to avoid repeated dynamic imports
let FileCryptoServiceCache = null;
const getFileCryptoService = async () => {
  if (!FileCryptoServiceCache) {
    const module = await import("../../../services/Crypto/FileCryptoService.js");
    FileCryptoServiceCache = module.default;
  }
  return FileCryptoServiceCache;
};

// UUID validation regex for tag IDs
const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;

const TagSearchResults = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const { getThemeClasses } = useUIXTheme();
  const { tagManager } = useTags();
  const { CollectionCryptoService } = useCrypto();
  const isMountedRef = useRef(true);

  // Get selected tag IDs from navigation state and validate
  const selectedTagIds = useMemo(() => {
    const rawIds = location.state?.selectedTagIds;
    if (!Array.isArray(rawIds)) return [];
    // Filter to only valid UUID strings
    return rawIds.filter(id => typeof id === 'string' && UUID_REGEX.test(id));
  }, [location.state?.selectedTagIds]);

  // State
  const [results, setResults] = useState(null);
  const [decryptedCollections, setDecryptedCollections] = useState([]);
  const [decryptedFiles, setDecryptedFiles] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isDecrypting, setIsDecrypting] = useState(false);
  const [error, setError] = useState("");

  // Cleanup on unmount
  useEffect(() => {
    isMountedRef.current = true;
    return () => {
      isMountedRef.current = false;
    };
  }, []);

  // Redirect if no tags selected
  useEffect(() => {
    if (!selectedTagIds || selectedTagIds.length === 0) {
      navigate("/me/tags/search");
    }
  }, [selectedTagIds, navigate]);

  // Decrypt search results
  const decryptResults = useCallback(async (searchResults) => {
    if (!isMountedRef.current) return;

    try {
      setIsDecrypting(true);

      // Decrypt collections
      if (searchResults.collections && searchResults.collections.length > 0) {
        const collectionPromises = searchResults.collections.map(async (collection) => {
          try {
            const decrypted = await CollectionCryptoService.decryptCollectionFromAPI(collection);
            return decrypted;
          } catch (error) {
            if (import.meta.env.DEV) {
              console.error("[TagSearchResults] Failed to decrypt collection:", collection.id, error);
            }
            return null;
          }
        });
        const decryptedColls = (await Promise.all(collectionPromises)).filter(Boolean);
        if (isMountedRef.current) {
          setDecryptedCollections(decryptedColls);
        }
      }

      // Decrypt files
      if (searchResults.files && searchResults.files.length > 0) {
        // Use cached FileCryptoService
        const FileCryptoService = await getFileCryptoService();

        const filePromises = searchResults.files.map(async (file) => {
          try {
            const decrypted = await FileCryptoService.decryptFileFromAPI(file);
            return decrypted;
          } catch (error) {
            if (import.meta.env.DEV) {
              console.error("[TagSearchResults] Failed to decrypt file:", file.id, error);
            }
            return null;
          }
        });
        const decryptedFileList = (await Promise.all(filePromises)).filter(Boolean);
        if (isMountedRef.current) {
          setDecryptedFiles(decryptedFileList);
        }
      }
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("[TagSearchResults] Decryption failed:", error);
      }
    } finally {
      if (isMountedRef.current) {
        setIsDecrypting(false);
      }
    }
  }, [CollectionCryptoService]);

  // Perform search
  const performSearch = useCallback(async () => {
    if (!tagManager || !isMountedRef.current) return;

    try {
      setIsLoading(true);
      setError("");
      if (import.meta.env.DEV) {
        console.log("[TagSearchResults] Searching with tags:", selectedTagIds);
      }

      const searchResults = await tagManager.searchByTags(selectedTagIds, 50);

      if (isMountedRef.current) {
        setResults(searchResults);

        if (import.meta.env.DEV) {
          console.log("[TagSearchResults] Search completed:", searchResults);
        }

        // Decrypt results
        await decryptResults(searchResults);
      }
    } catch (err) {
      if (isMountedRef.current) {
        if (import.meta.env.DEV) {
          console.error("[TagSearchResults] Search failed:", err);
        }
        setError(err.message || "Failed to search by tags");
      }
    } finally {
      if (isMountedRef.current) {
        setIsLoading(false);
      }
    }
  }, [tagManager, selectedTagIds, decryptResults]);

  // Perform search on mount
  useEffect(() => {
    if (selectedTagIds && selectedTagIds.length > 0 && tagManager) {
      performSearch();
    }
  }, [tagManager]); // Only run when tagManager becomes available

  // Format file size
  const formatFileSize = useCallback((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];
  }, []);

  // Format date
  const formatDate = useCallback((dateString) => {
    const date = new Date(dateString);
    return date.toLocaleDateString("en-US", {
      year: "numeric",
      month: "short",
      day: "numeric",
    });
  }, []);

  // Memoize breadcrumb items
  const breadcrumbItems = useMemo(() => [
    {
      label: "Settings",
      to: "/me",
      icon: Cog6ToothIcon,
    },
    {
      label: "Tags",
      to: "/me/tags",
      icon: TagIcon,
    },
    {
      label: "Search",
      to: "/me/tags/search",
      icon: MagnifyingGlassIcon,
    },
    {
      label: "Results",
      isActive: true,
    },
  ], []);

  // Calculate totals
  const totalCollections = results?.collectionCount || 0;
  const totalFiles = results?.fileCount || 0;
  const hasResults = totalCollections > 0 || totalFiles > 0;

  return (
    <Layout>
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Breadcrumb Navigation */}
        <Breadcrumb items={breadcrumbItems} />

        {/* Main Card */}
        <Card>
          {/* Header with icon, title, and action buttons */}
          <div className={`p-6 border-b ${getThemeClasses("border-secondary")}`}>
            <div className="flex flex-col space-y-4 lg:flex-row lg:items-center lg:justify-between lg:space-y-0">
              <div className="flex-1 min-w-0">
                <div className="flex items-start">
                  {/* Icon */}
                  <div className={`p-3 rounded-2xl shadow-lg mr-4 flex-shrink-0 ${getThemeClasses("bg-gradient-secondary")}`}>
                    <MagnifyingGlassIcon className="h-8 w-8 sm:h-10 sm:w-10 text-white" />
                  </div>
                  {/* Title and subtitle */}
                  <div>
                    <h1 className={`text-2xl sm:text-3xl lg:text-4xl font-bold ${getThemeClasses("text-primary")} leading-tight`}>
                      Search Results
                    </h1>
                    <p className={`mt-2 text-base sm:text-lg ${getThemeClasses("text-secondary")}`}>
                      Showing results for {selectedTagIds.length} selected tag{selectedTagIds.length !== 1 ? "s" : ""}
                    </p>
                  </div>
                </div>
              </div>
              {/* Action buttons */}
              <div className="flex-shrink-0 flex items-center space-x-3">
                <Button
                  onClick={() => navigate("/me/tags/search")}
                  variant="primary"
                  icon={MagnifyingGlassIcon}
                >
                  New Search
                </Button>
                <Button
                  onClick={() => navigate("/me/tags/search")}
                  variant="secondary"
                  size="sm"
                >
                  <span className="inline-flex items-center gap-2">
                    <ArrowLeftIcon className="h-4 w-4" />
                    <span>Back</span>
                  </span>
                </Button>
              </div>
            </div>
          </div>

          {/* Messages */}
          <div className="px-6 pt-6">
            {error && (
              <Alert type="error" className="mb-4" onClose={() => setError("")}>
                {error}
              </Alert>
            )}
          </div>

          {/* Content */}
          <div className="px-6 pb-3 pt-2">
            {/* Loading State */}
            {isLoading ? (
              <div className="flex items-center justify-center py-12">
                <div className="text-center">
                  <Spinner size="lg" className="mx-auto mb-4" />
                  <p className={getThemeClasses("text-secondary")}>Searching...</p>
                </div>
              </div>
            ) : results ? (
              <>
                {/* Summary Stats */}
                <div className={`mb-6 pb-4 border-b ${getThemeClasses("border-secondary")}`}>
                  <div className="flex items-center justify-between flex-wrap gap-4">
                    <div className="flex items-center space-x-6">
                      <div className="flex items-center">
                        <FolderIcon className={`h-6 w-6 mr-2 ${getThemeClasses("text-secondary")}`} />
                        <div>
                          <p className={`text-2xl font-bold ${getThemeClasses("text-primary")}`}>{totalCollections}</p>
                          <p className={`text-sm ${getThemeClasses("text-secondary")}`}>Collections</p>
                        </div>
                      </div>
                      <div className="flex items-center">
                        <DocumentIcon className={`h-6 w-6 mr-2 ${getThemeClasses("text-secondary")}`} />
                        <div>
                          <p className={`text-2xl font-bold ${getThemeClasses("text-primary")}`}>{totalFiles}</p>
                          <p className={`text-sm ${getThemeClasses("text-secondary")}`}>Files</p>
                        </div>
                      </div>
                    </div>
                    {isDecrypting && (
                      <div className="flex items-center">
                        <Spinner size="sm" className="mr-2" />
                        <span className={`text-sm ${getThemeClasses("text-secondary")}`}>Decrypting...</span>
                      </div>
                    )}
                  </div>
                </div>

                {/* No Results */}
                {!hasResults ? (
                  <div className="text-center py-3">
                    <div className={`h-20 w-20 ${getThemeClasses("bg-muted")} rounded-2xl flex items-center justify-center mx-auto mb-3`}>
                      <MagnifyingGlassIcon className="h-10 w-10 text-gray-400" />
                    </div>
                    <h3 className={`text-xl font-semibold mb-2 ${getThemeClasses("text-primary")}`}>
                      No results found
                    </h3>
                    <p className={`mb-6 ${getThemeClasses("text-secondary")}`}>
                      No collections or files match all the selected tags. Try selecting fewer tags.
                    </p>
                    <Button
                      onClick={() => navigate("/me/tags/search")}
                      icon={MagnifyingGlassIcon}
                      variant="primary"
                    >
                      Try Different Tags
                    </Button>
                  </div>
                ) : (
                  <div className="space-y-8">
                    {/* Collections Section */}
                    {decryptedCollections.length > 0 && (
                      <div>
                        <h2 className={`text-lg font-semibold mb-4 flex items-center ${getThemeClasses("text-primary")}`}>
                          <FolderIcon className={`h-5 w-5 mr-2 ${getThemeClasses("text-secondary")}`} />
                          Collections ({decryptedCollections.length})
                        </h2>
                        <div className="grid gap-4 md:grid-cols-2">
                          {decryptedCollections.map((collection) => (
                            <div
                              key={collection.id}
                              role="button"
                              tabIndex={0}
                              aria-label={`Open collection ${collection.name}`}
                              onClick={() => navigate(`/file-manager/collections/${collection.id}`)}
                              onKeyDown={(e) => {
                                if (e.key === "Enter" || e.key === " ") {
                                  e.preventDefault();
                                  navigate(`/file-manager/collections/${collection.id}`);
                                }
                              }}
                              className={`p-4 rounded-lg border ${getThemeClasses("border-secondary")} ${getThemeClasses("bg-card")} hover:shadow-md transition-all duration-200 cursor-pointer`}
                            >
                              <div className="flex items-start">
                                <div className={`flex-shrink-0 w-12 h-12 ${getThemeClasses("bg-gradient-secondary")} rounded-lg flex items-center justify-center`}>
                                  <FolderIcon className="h-6 w-6 text-white" />
                                </div>
                                <div className="ml-4 flex-1 min-w-0">
                                  <h3 className={`text-base font-semibold truncate ${getThemeClasses("text-primary")}`}>
                                    {collection.name}
                                  </h3>
                                  {collection.description && (
                                    <p className={`mt-1 text-sm line-clamp-2 ${getThemeClasses("text-secondary")}`}>
                                      {collection.description}
                                    </p>
                                  )}
                                  <p className={`mt-2 text-xs ${getThemeClasses("text-muted")}`}>
                                    Created {formatDate(collection.created_at)}
                                  </p>
                                </div>
                              </div>
                            </div>
                          ))}
                        </div>
                      </div>
                    )}

                    {/* Files Section */}
                    {decryptedFiles.length > 0 && (
                      <div>
                        <h2 className={`text-lg font-semibold mb-4 flex items-center ${getThemeClasses("text-primary")}`}>
                          <DocumentIcon className={`h-5 w-5 mr-2 ${getThemeClasses("text-secondary")}`} />
                          Files ({decryptedFiles.length})
                        </h2>
                        <div className="grid gap-4 md:grid-cols-2">
                          {decryptedFiles.map((file) => (
                            <div
                              key={file.id}
                              role="button"
                              tabIndex={0}
                              aria-label={`Open file ${file.filename}`}
                              onClick={() => navigate(`/file-manager/files/${file.id}`)}
                              onKeyDown={(e) => {
                                if (e.key === "Enter" || e.key === " ") {
                                  e.preventDefault();
                                  navigate(`/file-manager/files/${file.id}`);
                                }
                              }}
                              className={`p-4 rounded-lg border ${getThemeClasses("border-secondary")} ${getThemeClasses("bg-card")} hover:shadow-md transition-all duration-200 cursor-pointer`}
                            >
                              <div className="flex items-start">
                                <div className="flex-shrink-0 w-12 h-12 bg-blue-500 rounded-lg flex items-center justify-center">
                                  <DocumentIcon className="h-6 w-6 text-white" />
                                </div>
                                <div className="ml-4 flex-1 min-w-0">
                                  <h3 className={`text-base font-semibold truncate ${getThemeClasses("text-primary")}`}>
                                    {file.filename}
                                  </h3>
                                  <p className={`mt-2 text-xs ${getThemeClasses("text-muted")}`}>
                                    {formatFileSize(file.size_in_bytes)} • Uploaded {formatDate(file.created_at)}
                                  </p>
                                </div>
                              </div>
                            </div>
                          ))}
                        </div>
                      </div>
                    )}
                  </div>
                )}

                {/* Info Box */}
                <div className={`mt-6 p-4 rounded-lg border ${getThemeClasses("border-secondary")} ${getThemeClasses("bg-muted")}`}>
                  <div className="flex">
                    <div className="flex-shrink-0">
                      <InformationCircleIcon className={`h-5 w-5 ${getThemeClasses("text-info")}`} />
                    </div>
                    <div className="ml-3">
                      <h3 className={`text-sm font-medium ${getThemeClasses("text-primary")}`}>
                        About these results
                      </h3>
                      <p className={`mt-1 text-sm ${getThemeClasses("text-secondary")}`}>
                        These results show items that have <strong>ALL</strong> of your selected tags.
                        Click on any item to view its details.
                      </p>
                    </div>
                  </div>
                </div>
              </>
            ) : null}
          </div>
        </Card>
      </div>
    </Layout>
  );
};

export default withPasswordProtection(TagSearchResults);
