// File: src/pages/User/Tags/TagEdit.jsx
// Tag Edit Page - Edit an existing tag

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

const TagEdit = () => {
  const navigate = useNavigate();
  const { tagId } = useParams();
  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 [formData, setFormData] = useState({ name: "", color: "#3B82F6" });
  const [formErrors, setFormErrors] = useState({});

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

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

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

      if (!isMountedRef.current) return;

      const tag = tags.find((t) => t.id === tagId);
      if (!tag) {
        setError("Tag not found");
        setTimeout(() => navigate("/me/tags"), 2000);
        return;
      }
      setFormData({ name: tag.name, color: tag.color });
      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]);

  useEffect(() => {
    if (tagManager && !isInitialized) {
      loadTag();
    }
  }, [tagManager, isInitialized, loadTag]);

  // Handle update
  const handleUpdate = useCallback(async (e) => {
    e.preventDefault();

    if (!isMountedRef.current) return;

    try {
      setFormErrors({});
      setError("");

      // Validate
      const errors = {};
      if (!formData.name.trim()) {
        errors.name = "Tag name is required";
      }
      if (!formData.color) {
        errors.color = "Tag color is required";
      }

      if (Object.keys(errors).length > 0) {
        setFormErrors(errors);
        return;
      }

      setIsLoading(true);
      await tagManager.updateTag(tagId, formData);

      if (!isMountedRef.current) return;

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

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

  // Breadcrumb items
  const breadcrumbItems = [
    { label: "Settings", to: "/me", icon: Cog6ToothIcon },
    { label: "Tags", to: "/me/tags", icon: TagIcon },
    { label: "Edit 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-gradient-secondary")}`}>
                    <TagIcon 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`}>
                      Edit Tag
                    </h1>
                    <p className={`mt-2 text-base sm:text-lg ${getThemeClasses("text-secondary")}`}>
                      Update tag information
                    </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 && !formData.name ? (
              <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>
            ) : (
              <form onSubmit={handleUpdate} className="space-y-6 max-w-xl">
                <Input
                  label="Tag Name"
                  type="text"
                  name="tag_name"
                  placeholder="e.g., Important, Work, Personal"
                  value={formData.name}
                  onChange={(value) => {
                    setFormData({ ...formData, name: value });
                    setFormErrors({ ...formErrors, name: "" });
                  }}
                  maxLength={50}
                  required
                  disabled={isLoading}
                  error={formErrors.name}
                  icon={TagIcon}
                />

                <div>
                  <label className={`block text-sm font-medium ${getThemeClasses("text-primary")} mb-2`}>
                    Tag Color <span className={getThemeClasses("text-error")}>*</span>
                  </label>
                  <div className="flex items-center space-x-4">
                    <input
                      type="color"
                      value={formData.color}
                      onChange={(e) => {
                        setFormData({ ...formData, color: e.target.value });
                        setFormErrors({ ...formErrors, color: "" });
                      }}
                      className={`h-12 w-24 rounded-lg cursor-pointer border-2 ${getThemeClasses("border-muted")} shadow-sm ${getThemeClasses("hover:border-accent")} transition-colors duration-200`}
                      disabled={isLoading}
                    />
                    <div className="flex-1">
                      <Input
                        type="text"
                        name="tag_color"
                        placeholder="#3B82F6"
                        value={formData.color}
                        onChange={(value) => {
                          setFormData({ ...formData, color: value });
                          setFormErrors({ ...formErrors, color: "" });
                        }}
                        maxLength={7}
                        disabled={isLoading}
                        error={formErrors.color}
                      />
                    </div>
                  </div>
                  <p className={`text-xs ${getThemeClasses("text-secondary")} mt-2`}>
                    Choose a color to identify this tag visually
                  </p>
                </div>

                <div className={`flex space-x-3 pt-4 border-t ${getThemeClasses("border-muted")}`}>
                  <Button
                    type="submit"
                    variant="primary"
                    disabled={isLoading}
                    loading={isLoading}
                  >
                    {!isLoading && "Update Tag"}
                    {isLoading && "Updating..."}
                  </Button>
                  <Button
                    type="button"
                    variant="secondary"
                    onClick={() => navigate("/me/tags")}
                    disabled={isLoading}
                  >
                    Cancel
                  </Button>
                </div>
              </form>
            )}
          </div>
        </Card>
      </div>
    </Layout>
  );
};

export default withPasswordProtection(TagEdit);
