// File: src/pages/User/Tags/TagList.jsx
// Tags List Page - Display all user tags with Layout (sidebar + topbar)

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,
  useUIXTheme,
} from "../../../components/UIX";
import {
  PlusIcon,
  TagIcon,
  PencilIcon,
  TrashIcon,
  ArrowLeftIcon,
  Cog6ToothIcon,
} from "@heroicons/react/24/outline";

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

  // State
  const [tags, setTags] = useState([]);
  const [isLoading, setIsLoading] = useState(true); // Start with loading true
  const [isInitialized, setIsInitialized] = useState(false);
  const [error, setError] = useState("");
  const [success, setSuccess] = 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]);

  // Listen for tag events
  useEffect(() => {
    const handleTagCreated = () => loadTags();
    const handleTagUpdated = () => loadTags();
    const handleTagDeleted = () => loadTags();

    window.addEventListener("tagCreated", handleTagCreated);
    window.addEventListener("tagUpdated", handleTagUpdated);
    window.addEventListener("tagDeleted", handleTagDeleted);

    return () => {
      window.removeEventListener("tagCreated", handleTagCreated);
      window.removeEventListener("tagUpdated", handleTagUpdated);
      window.removeEventListener("tagDeleted", handleTagDeleted);
    };
  }, [loadTags]);

  // Handle delete
  const handleDelete = useCallback((tagId, tagName) => {
    navigate(`/me/tags/${tagId}/delete`, { state: { tagName } });
  }, [navigate]);

  // Memoize breadcrumb items
  const breadcrumbItems = useMemo(() => [
    {
      label: "Settings",
      to: "/me",
      icon: Cog6ToothIcon,
    },
    {
      label: "Tags",
      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 button */}
          <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")}`}>
                    <TagIcon 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`}>
                      Manage Tags
                    </h1>
                    <p className={`mt-2 text-base sm:text-lg ${getThemeClasses("text-secondary")}`}>
                      Create and organize tags for your files and collections
                    </p>
                  </div>
                </div>
              </div>
              {/* Action buttons */}
              <div className="flex-shrink-0 flex items-center space-x-3">
                <Button
                  onClick={() => navigate("/me/tags/create")}
                  icon={PlusIcon}
                  variant="primary"
                >
                  New Tag
                </Button>
                <Button
                  onClick={() => navigate("/me")}
                  variant="secondary"
                  size="sm"
                >
                  <span className="inline-flex items-center gap-2">
                    <ArrowLeftIcon className="h-4 w-4" />
                    <span>Back to Settings</span>
                  </span>
                </Button>
              </div>
            </div>
          </div>

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

          {/* Content */}
          <div className="px-6 pb-6 pt-2">
            {/* Tags List */}
            {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 yet
                </h3>
                <p className={`mb-6 ${getThemeClasses("text-secondary")}`}>
                  Create your first tag to organize your files
                </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) => (
                  <div
                    key={tag.id}
                    role="article"
                    aria-label={`Tag: ${tag.name}`}
                    className={`p-4 rounded-lg border ${getThemeClasses("border-secondary")} ${getThemeClasses("bg-card")} ${getThemeClasses("hover:shadow")} transition-shadow duration-200`}
                  >
                    <div className="flex items-start justify-between">
                      <div className="flex items-center space-x-3 flex-1 min-w-0">
                        <div
                          className="w-5 h-5 rounded-full flex-shrink-0 shadow-sm"
                          style={{ backgroundColor: tag.color }}
                          aria-hidden="true"
                        />
                        <div className="flex-1 min-w-0">
                          <h4 className={`text-sm font-medium truncate ${getThemeClasses("text-primary")}`}>
                            {tag.name}
                          </h4>
                          <p className={`text-xs mt-0.5 ${getThemeClasses("text-secondary")}`}>
                            {tag.color}
                          </p>
                        </div>
                      </div>
                      <div className="flex space-x-1 ml-2" role="group" aria-label={`Actions for tag ${tag.name}`}>
                        <Button
                          onClick={() => navigate(`/me/tags/${tag.id}/edit`)}
                          variant="ghost"
                          size="sm"
                          aria-label={`Edit tag ${tag.name}`}
                        >
                          <PencilIcon className="h-4 w-4" />
                        </Button>
                        <Button
                          onClick={() => handleDelete(tag.id, tag.name)}
                          variant="ghost"
                          size="sm"
                          aria-label={`Delete tag ${tag.name}`}
                          className="hover:text-red-600 dark:hover:text-red-400"
                        >
                          <TrashIcon className="h-4 w-4" />
                        </Button>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </Card>
      </div>
    </Layout>
  );
};

export default withPasswordProtection(TagList);
