// File: src/pages/User/Tags/TagSearch.jsx
// Tag Search Page - Select tags and search for collections and files
// Layout pattern matching FileManagerIndex.jsx

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

const TagSearch = () => {
  const navigate = useNavigate();
  const { getThemeClasses } = useUIXTheme();
  const { tagManager } = useTags();
  const isMountedRef = useRef(true);

  // State
  const [tags, setTags] = useState([]);
  const [selectedTagIds, setSelectedTagIds] = useState([]);
  const [isLoading, setIsLoading] = useState(true); // Start with loading true
  const [isInitialized, setIsInitialized] = useState(false);
  const [error, setError] = useState("");

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

  // Load tags
  const loadTags = useCallback(async () => {
    if (!tagManager) return;

    try {
      setIsLoading(true);
      setError("");
      const fetchedTags = await tagManager.listTags();
      if (isMountedRef.current) {
        setTags(fetchedTags || []);
        setIsInitialized(true);
      }
    } catch (err) {
      if (isMountedRef.current) {
        if (import.meta.env.DEV) {
          console.error("Failed to load tags:", err);
        }
        setError(err.message || "Failed to load tags");
        setIsInitialized(true);
      }
    } finally {
      if (isMountedRef.current) {
        setIsLoading(false);
      }
    }
  }, [tagManager]);

  // Load tags when tagManager becomes available
  useEffect(() => {
    if (tagManager && !isInitialized) {
      loadTags();
    }
  }, [tagManager, isInitialized, loadTags]);

  // Toggle tag selection
  const handleTagToggle = useCallback((tagId) => {
    setSelectedTagIds((prev) =>
      prev.includes(tagId)
        ? prev.filter((id) => id !== tagId)
        : [...prev, tagId]
    );
  }, []);

  // Handle search
  const handleSearch = useCallback(() => {
    if (selectedTagIds.length === 0) {
      setError("Please select at least one tag to search");
      return;
    }

    // Navigate to results page with selected tag IDs
    navigate("/me/tags/search/results", {
      state: { selectedTagIds },
    });
  }, [selectedTagIds, navigate]);

  // Clear selection
  const handleClearSelection = useCallback(() => {
    setSelectedTagIds([]);
    setError("");
  }, []);

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

  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 by Tags
                    </h1>
                    <p className={`mt-2 text-base sm:text-lg ${getThemeClasses("text-secondary")}`}>
                      Select tags to find matching files and collections
                    </p>
                  </div>
                </div>
              </div>
              {/* Action buttons */}
              <div className="flex-shrink-0 flex items-center space-x-3">
                <Button
                  onClick={handleSearch}
                  disabled={selectedTagIds.length === 0}
                  variant="primary"
                  icon={MagnifyingGlassIcon}
                >
                  Search {selectedTagIds.length > 0 && `(${selectedTagIds.length})`}
                </Button>
                <Button
                  onClick={() => navigate("/me/tags")}
                  variant="secondary"
                  size="sm"
                >
                  <span className="inline-flex items-center gap-2">
                    <ArrowLeftIcon className="h-4 w-4" />
                    <span>Back to Tags</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-6 pt-2">
            {/* Selection Counter */}
            <div className={`mb-6 pb-4 border-b ${getThemeClasses("border-secondary")}`}>
              <div className="flex items-center justify-between">
                <div className="flex items-center">
                  <TagIcon className={`h-5 w-5 mr-2 ${getThemeClasses("text-secondary")}`} />
                  <span className={`text-sm font-medium ${getThemeClasses("text-primary")}`}>
                    {selectedTagIds.length} tag{selectedTagIds.length !== 1 ? "s" : ""} selected
                  </span>
                </div>
                {selectedTagIds.length > 0 && (
                  <Button
                    onClick={handleClearSelection}
                    variant="ghost"
                    size="sm"
                  >
                    Clear All
                  </Button>
                )}
              </div>
            </div>

            {/* Tags Grid */}
            {isLoading && tags.length === 0 ? (
              <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")}>Loading tags...</p>
                </div>
              </div>
            ) : tags.length === 0 ? (
              <div className="text-center py-12">
                <div className={`h-20 w-20 ${getThemeClasses("bg-muted")} rounded-2xl flex items-center justify-center mx-auto mb-3`}>
                  <TagIcon className="h-10 w-10 text-gray-400" />
                </div>
                <h3 className={`text-xl font-semibold mb-2 ${getThemeClasses("text-primary")}`}>
                  No tags available
                </h3>
                <p className={`mb-6 ${getThemeClasses("text-secondary")}`}>
                  Create tags first before searching
                </p>
                <Button
                  onClick={() => navigate("/me/tags/create")}
                  icon={PlusIcon}
                  variant="primary"
                >
                  Create Your First Tag
                </Button>
              </div>
            ) : (
              <>
                <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
                  {tags.map((tag) => {
                    const isSelected = selectedTagIds.includes(tag.id);
                    return (
                      <div
                        key={tag.id}
                        role="button"
                        tabIndex={0}
                        aria-label={`${isSelected ? "Deselect" : "Select"} tag ${tag.name}`}
                        aria-pressed={isSelected}
                        onClick={() => handleTagToggle(tag.id)}
                        onKeyDown={(e) => {
                          if (e.key === "Enter" || e.key === " ") {
                            e.preventDefault();
                            handleTagToggle(tag.id);
                          }
                        }}
                        className={`p-4 rounded-lg border-2 cursor-pointer transition-all duration-200 ${
                          isSelected
                            ? `${getThemeClasses("border-primary")} ${getThemeClasses("bg-accent-light")} shadow-md`
                            : `${getThemeClasses("border-secondary")} ${getThemeClasses("bg-card")} ${getThemeClasses("hover:border-primary")} hover:shadow-sm`
                        }`}
                      >
                        <div className="flex items-center space-x-3">
                          <div onClick={(e) => e.stopPropagation()}>
                            <Checkbox
                              checked={isSelected}
                              onChange={() => handleTagToggle(tag.id)}
                            />
                          </div>
                          <div
                            className="w-5 h-5 rounded-full flex-shrink-0 shadow-sm"
                            style={{ backgroundColor: tag.color }}
                          />
                          <div className="flex-1 min-w-0">
                            <h4 className={`text-base font-semibold truncate ${getThemeClasses("text-primary")}`}>
                              {tag.name}
                            </h4>
                          </div>
                          {isSelected && (
                            <div className={`flex-shrink-0 w-6 h-6 ${getThemeClasses("bg-gradient-secondary")} rounded-full flex items-center justify-center`}>
                              <CheckIcon className="w-4 h-4 text-white" />
                            </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")}`}>
                        How tag search works
                      </h3>
                      <p className={`mt-1 text-sm ${getThemeClasses("text-secondary")}`}>
                        Search returns items that have <strong>ALL</strong> selected tags (AND logic).
                        The more tags you select, the more specific your search becomes.
                      </p>
                    </div>
                  </div>
                </div>
              </>
            )}
          </div>
        </Card>
      </div>
    </Layout>
  );
};

export default withPasswordProtection(TagSearch);
