// File: src/pages/User/Tags/TagDelete.jsx
// Tag Delete Page - Delete confirmation for a tag

import React, { useState, useEffect, useRef, useCallback } from "react";
import { useNavigate, useParams, useLocation } 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 {
  ArrowLeftIcon,
  ExclamationTriangleIcon,
  TagIcon,
  TrashIcon,
  Cog6ToothIcon,
} from "@heroicons/react/24/outline";

const TagDelete = () => {
  const navigate = useNavigate();
  const { tagId } = useParams();
  const location = useLocation();
  const { tagManager } = useTags();
  const { getThemeClasses } = useUIXTheme();
  const isMountedRef = useRef(true);

  // State
  const [isLoading, setIsLoading] = useState(false);
  const [isInitialized, setIsInitialized] = useState(false);
  const [error, setError] = useState("");
  const [tag, setTag] = useState(null);

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

  // Load tag
  const loadTag = useCallback(async () => {
    if (!tagManager) return;

    try {
      setIsLoading(true);
      setError("");
      const tags = await tagManager.listTags();

      if (!isMountedRef.current) return;

      const foundTag = tags.find((t) => t.id === tagId);
      if (!foundTag) {
        setError("Tag not found");
        setTimeout(() => navigate("/me/tags"), 2000);
        return;
      }
      setTag(foundTag);
      setIsInitialized(true);
    } catch (err) {
      if (!isMountedRef.current) return;

      if (import.meta.env.DEV) {
        console.error("Failed to load tag:", err);
      }
      setError(err.message || "Failed to load tag");
      setIsInitialized(true);
    } finally {
      if (isMountedRef.current) {
        setIsLoading(false);
      }
    }
  }, [tagManager, tagId, navigate]);

  // Get tag name from location state or load tag
  useEffect(() => {
    if (location.state?.tagName) {
      setTag({ id: tagId, name: location.state.tagName });
      setIsInitialized(true);
    } else if (tagManager && !isInitialized) {
      loadTag();
    }
  }, [tagId, location.state, tagManager, isInitialized, loadTag]);

  // Handle delete
  const handleDelete = useCallback(async () => {
    if (!isMountedRef.current) return;

    try {
      setError("");
      setIsLoading(true);

      if (import.meta.env.DEV) {
        console.log("[TagDelete] Attempting to delete tag:", tagId);
      }

      await tagManager.deleteTag(tagId);

      if (!isMountedRef.current) return;

      if (import.meta.env.DEV) {
        console.log("[TagDelete] Tag deleted successfully");
      }

      // Navigate back to list
      navigate("/me/tags");
    } catch (err) {
      if (!isMountedRef.current) return;

      if (import.meta.env.DEV) {
        console.error("[TagDelete] Failed to delete tag:", err);
      }
      setError(err.message || "Failed to delete tag");
      setIsLoading(false);
    }
  }, [tagManager, tagId, navigate]);

  // Breadcrumb items
  const breadcrumbItems = [
    { label: "Settings", to: "/me", icon: Cog6ToothIcon },
    { label: "Tags", to: "/me/tags", icon: TagIcon },
    { label: "Delete Tag", 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 */}
          <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">
                  <div className={`p-3 rounded-2xl shadow-lg mr-4 flex-shrink-0 ${getThemeClasses("bg-error")}`}>
                    <TrashIcon className="h-8 w-8 sm:h-10 sm:w-10 text-white" />
                  </div>
                  <div>
                    <h1 className={`text-2xl sm:text-3xl lg:text-4xl font-bold ${getThemeClasses("text-primary")} leading-tight`}>
                      Delete Tag
                    </h1>
                    <p className={`mt-2 text-base sm:text-lg ${getThemeClasses("text-secondary")}`}>
                      Confirm tag deletion
                    </p>
                  </div>
                </div>
              </div>
              <div className="flex-shrink-0">
                <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">
            {isLoading && !tag ? (
              <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 tag...</p>
                </div>
              </div>
            ) : tag ? (
              <div className="max-w-xl">
                <div className={`${getThemeClasses("bg-error-light")} border ${getThemeClasses("border-error")} rounded-xl p-6`}>
                  <div className="flex items-start space-x-4">
                    <div className="flex-shrink-0">
                      <div className={`inline-flex items-center justify-center w-14 h-14 rounded-2xl ${getThemeClasses("bg-error-light")}`}>
                        <ExclamationTriangleIcon className={`h-8 w-8 ${getThemeClasses("text-error")}`} />
                      </div>
                    </div>
                    <div className="flex-1">
                      <h3 className={`text-xl font-semibold ${getThemeClasses("text-primary")} mb-2`}>
                        Delete Tag "{tag.name}"?
                      </h3>
                      <div className="space-y-2">
                        <p className={`text-sm ${getThemeClasses("text-secondary")}`}>
                          Are you sure you want to delete this tag? This action cannot
                          be undone.
                        </p>
                        <Alert type="info" className="mt-4">
                          <strong>Note:</strong> This will only delete the tag itself. Files and
                          collections with this tag will not be affected.
                        </Alert>
                      </div>
                    </div>
                  </div>
                </div>

                <div className={`flex space-x-3 mt-6 pt-6 border-t ${getThemeClasses("border-muted")}`}>
                  <Button
                    onClick={handleDelete}
                    variant="danger"
                    disabled={isLoading}
                    loading={isLoading}
                  >
                    {!isLoading && (
                      <span className="inline-flex items-center gap-2">
                        <TrashIcon className="h-4 w-4" />
                        <span>Delete Tag</span>
                      </span>
                    )}
                    {isLoading && "Deleting..."}
                  </Button>
                  <Button
                    onClick={() => navigate("/me/tags")}
                    variant="secondary"
                    disabled={isLoading}
                  >
                    Cancel
                  </Button>
                </div>
              </div>
            ) : null}
          </div>
        </Card>
      </div>
    </Layout>
  );
};

export default withPasswordProtection(TagDelete);
