// File: src/pages/User/Tags/TagCreate.jsx
// Tag Create Page - Create a new tag

import React, { useState, useRef, useEffect, useCallback } 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,
  Input,
  Alert,
  Card,
  Breadcrumb,
  useUIXTheme,
} from "../../../components/UIX";
import {
  ArrowLeftIcon,
  TagIcon,
  PlusIcon,
  Cog6ToothIcon,
} from "@heroicons/react/24/outline";

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

  // State
  const [isLoading, setIsLoading] = 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;
    };
  }, []);

  // Handle create
  const handleCreate = 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.createTag(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 create tag:", err);
      }
      setError(err.message || "Failed to create tag");
    } finally {
      if (isMountedRef.current) {
        setIsLoading(false);
      }
    }
  }, [formData, tagManager, navigate]);

  // Breadcrumb items
  const breadcrumbItems = [
    { label: "Settings", to: "/me", icon: Cog6ToothIcon },
    { label: "Tags", to: "/me/tags", icon: TagIcon },
    { label: "Create 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")}`}>
                    <PlusIcon 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`}>
                      Create Tag
                    </h1>
                    <p className={`mt-2 text-base sm:text-lg ${getThemeClasses("text-secondary")}`}>
                      Create a new tag to organize your files and collections
                    </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">
            <form onSubmit={handleCreate} 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 && (
                    <span className="inline-flex items-center gap-2">
                      <PlusIcon className="h-4 w-4" />
                      <span>Create Tag</span>
                    </span>
                  )}
                  {isLoading && "Creating..."}
                </Button>
                <Button
                  type="button"
                  variant="secondary"
                  onClick={() => navigate("/me/tags")}
                  disabled={isLoading}
                >
                  Cancel
                </Button>
              </div>
            </form>
          </div>
        </Card>
      </div>
    </Layout>
  );
};

export default withPasswordProtection(TagCreate);
