// File Path: monorepo/native/desktop/maplefile/frontend/src/pages/User/Tags/TagEdit.jsx
import { useState, useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
import Navigation from "../../../components/Navigation";
import Page from "../../../components/Page";
import {
  ListTags,
  UpdateTag,
} from "../../../../wailsjs/go/app/Application";

function TagEdit() {
  const navigate = useNavigate();
  const { tagId } = useParams();
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [error, setError] = useState("");
  const [formData, setFormData] = useState({
    name: "",
    color: "#3B82F6"
  });
  const [formErrors, setFormErrors] = useState({});

  useEffect(() => {
    loadTag();
  }, [tagId]);

  const loadTag = async () => {
    try {
      setIsLoading(true);
      setError("");

      // Fetch all tags and find the one we need
      const tags = await ListTags();
      const tag = tags.find((t) => t.id === tagId);

      if (!tag) {
        setError("Tag not found");
        setTimeout(() => navigate("/me?tab=tags"), 2000);
        return;
      }

      setFormData({
        name: tag.name,
        color: tag.color
      });
    } catch (err) {
      console.error("Failed to load tag:", err);
      setError(err.message || "Failed to load tag");
    } finally {
      setIsLoading(false);
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    // 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;
    }

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

      await UpdateTag(tagId, formData.name.trim(), formData.color);

      // Navigate back to profile page with tags tab selected
      navigate("/me?tab=tags");
    } catch (err) {
      console.error("Failed to update tag:", err);
      setError(err.message || "Failed to update tag");
    } finally {
      setIsSaving(false);
    }
  };

  return (
    <Page>
      <Navigation />
      <div style={{ maxWidth: "800px", margin: "0 auto", padding: "20px" }}>
        {/* Header */}
        <div style={{ marginBottom: "30px" }}>
          <button
            onClick={() => navigate("/me?tab=tags")}
            className="nav-button secondary"
            style={{ marginBottom: "16px" }}
          >
            ← Back to Tags
          </button>
          <h1 style={{ margin: "0 0 8px 0", fontSize: "28px", fontWeight: "600" }}>
            Edit Tag
          </h1>
          <p style={{ margin: 0, color: "#666" }}>
            Update tag information
          </p>
        </div>

        {/* Error Alert */}
        {error && (
          <div style={{
            padding: "12px",
            marginBottom: "20px",
            backgroundColor: "#fee",
            border: "1px solid #fcc",
            borderRadius: "4px",
            color: "#c00"
          }}>
            {error}
          </div>
        )}

        {/* Loading or Form */}
        {isLoading ? (
          <div style={{
            backgroundColor: "#fff",
            padding: "40px",
            borderRadius: "8px",
            border: "1px solid #e0e0e0",
            textAlign: "center"
          }}>
            <p>Loading tag...</p>
          </div>
        ) : (
          <div style={{
            backgroundColor: "#fff",
            padding: "24px",
            borderRadius: "8px",
            border: "1px solid #e0e0e0",
            boxShadow: "0 1px 3px rgba(0,0,0,0.1)"
          }}>
            <form onSubmit={handleSubmit}>
              {/* Tag Name */}
              <div style={{ marginBottom: "20px" }}>
                <label
                  htmlFor="tag_name"
                  style={{
                    display: "block",
                    marginBottom: "8px",
                    fontWeight: "500",
                    fontSize: "14px"
                  }}
                >
                  Tag Name <span style={{ color: "#c00" }}>*</span>
                </label>
                <input
                  id="tag_name"
                  type="text"
                  value={formData.name}
                  onChange={(e) => {
                    setFormData({ ...formData, name: e.target.value });
                    setFormErrors({ ...formErrors, name: "" });
                  }}
                  placeholder="e.g., Important, Work, Personal"
                  maxLength={50}
                  required
                  disabled={isSaving}
                  style={{
                    width: "100%",
                    padding: "10px 12px",
                    fontSize: "14px",
                    border: formErrors.name ? "1px solid #c00" : "1px solid #ccc",
                    borderRadius: "4px",
                    outline: "none",
                    boxSizing: "border-box"
                  }}
                />
                {formErrors.name && (
                  <p style={{ margin: "6px 0 0 0", fontSize: "13px", color: "#c00" }}>
                    {formErrors.name}
                  </p>
                )}
              </div>

              {/* Tag Color */}
              <div style={{ marginBottom: "24px" }}>
                <label
                  style={{
                    display: "block",
                    marginBottom: "8px",
                    fontWeight: "500",
                    fontSize: "14px"
                  }}
                >
                  Tag Color <span style={{ color: "#c00" }}>*</span>
                </label>
                <div style={{ display: "flex", gap: "16px", alignItems: "center" }}>
                  <input
                    type="color"
                    value={formData.color}
                    onChange={(e) => {
                      setFormData({ ...formData, color: e.target.value });
                      setFormErrors({ ...formErrors, color: "" });
                    }}
                    disabled={isSaving}
                    style={{
                      width: "80px",
                      height: "48px",
                      border: "2px solid #ccc",
                      borderRadius: "6px",
                      cursor: "pointer"
                    }}
                  />
                  <div style={{ flex: 1 }}>
                    <input
                      type="text"
                      value={formData.color}
                      onChange={(e) => {
                        setFormData({ ...formData, color: e.target.value });
                        setFormErrors({ ...formErrors, color: "" });
                      }}
                      placeholder="#3B82F6"
                      maxLength={7}
                      disabled={isSaving}
                      style={{
                        width: "100%",
                        padding: "10px 12px",
                        fontSize: "14px",
                        border: formErrors.color ? "1px solid #c00" : "1px solid #ccc",
                        borderRadius: "4px",
                        outline: "none",
                        fontFamily: "monospace",
                        boxSizing: "border-box"
                      }}
                    />
                  </div>
                </div>
                {formErrors.color && (
                  <p style={{ margin: "6px 0 0 0", fontSize: "13px", color: "#c00" }}>
                    {formErrors.color}
                  </p>
                )}
                <p style={{ margin: "8px 0 0 0", fontSize: "12px", color: "#666" }}>
                  Choose a color to identify this tag visually
                </p>
              </div>

              {/* Buttons */}
              <div style={{ display: "flex", gap: "12px", paddingTop: "16px", borderTop: "1px solid #e0e0e0" }}>
                <button
                  type="submit"
                  disabled={isSaving}
                  className="nav-button"
                  style={{
                    padding: "10px 20px",
                    cursor: isSaving ? "wait" : "pointer"
                  }}
                >
                  {isSaving ? "Updating..." : "Update Tag"}
                </button>
                <button
                  type="button"
                  onClick={() => navigate("/me?tab=tags")}
                  disabled={isSaving}
                  className="nav-button secondary"
                  style={{
                    padding: "10px 20px"
                  }}
                >
                  Cancel
                </button>
              </div>
            </form>
          </div>
        )}
      </div>
    </Page>
  );
}

export default TagEdit;
