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

function TagsList() {
  const navigate = useNavigate();
  const [tags, setTags] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState("");
  const [deleteError, setDeleteError] = useState("");
  const [deletingTagId, setDeletingTagId] = useState(null);
  const [confirmDelete, setConfirmDelete] = useState(null); // { tagId, tagName }

  useEffect(() => {
    loadTags();
  }, []);

  const loadTags = async () => {
    try {
      setIsLoading(true);
      setError("");
      const fetchedTags = await ListTags();
      setTags(fetchedTags || []);
    } catch (err) {
      console.error("Failed to load tags:", err);
      setError(err.message || "Failed to load tags");
    } finally {
      setIsLoading(false);
    }
  };

  const handleDeleteClick = (tagId, tagName) => {
    console.log("[TagsList] Delete button clicked:", tagId, tagName);
    setConfirmDelete({ tagId, tagName });
  };

  const handleDeleteConfirm = async () => {
    if (!confirmDelete) return;

    const { tagId, tagName } = confirmDelete;

    try {
      setDeletingTagId(tagId);
      setDeleteError("");
      setConfirmDelete(null);

      console.log("[TagsList] Deleting tag:", tagId, tagName);
      const result = await DeleteTag(tagId);
      console.log("[TagsList] Delete result:", result);

      // Reload tags after successful deletion
      console.log("[TagsList] Reloading tags after delete");
      await loadTags();
      console.log("[TagsList] Tags reloaded successfully");
    } catch (err) {
      console.error("[TagsList] Failed to delete tag:", err);
      console.error("[TagsList] Error details:", {
        message: err.message,
        stack: err.stack,
        error: err
      });
      setDeleteError(err.message || "Failed to delete tag");
    } finally {
      setDeletingTagId(null);
    }
  };

  const handleDeleteCancel = () => {
    console.log("[TagsList] Delete cancelled");
    setConfirmDelete(null);
  };

  if (isLoading) {
    return (
      <div style={{ textAlign: "center", padding: "40px" }}>
        <p>Loading tags...</p>
      </div>
    );
  }

  return (
    <div>
      {/* Header with Buttons */}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "20px" }}>
        <div>
          <h2 style={{ margin: 0, fontSize: "24px", fontWeight: "600" }}>Tags</h2>
          <p style={{ margin: "5px 0 0 0", color: "#666", fontSize: "14px" }}>
            Create and organize tags for your files and collections
          </p>
        </div>
        <div style={{ display: "flex", gap: "10px", marginLeft: "auto" }}>
          <button
            onClick={() => navigate("/tags/search")}
            className="nav-button"
            style={{ background: "#1976d2", color: "white" }}
          >
            🔍 Search by Tags
          </button>
          <button
            onClick={() => navigate("/me/tags/create")}
            className="nav-button"
          >
            + New Tag
          </button>
        </div>
      </div>

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

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

      {/* Tags List */}
      {tags.length === 0 ? (
        <div style={{
          textAlign: "center",
          padding: "60px 20px",
          backgroundColor: "#f9f9f9",
          borderRadius: "8px",
          border: "2px dashed #ddd"
        }}>
          <h3 style={{ margin: "0 0 10px 0", color: "#666" }}>No tags yet</h3>
          <p style={{ margin: "0 0 20px 0", color: "#999" }}>
            Create your first tag to organize your files and collections
          </p>
          <button
            onClick={() => navigate("/me/tags/create")}
            className="nav-button"
          >
            + Create Your First Tag
          </button>
        </div>
      ) : (
        <div style={{
          display: "grid",
          gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))",
          gap: "16px"
        }}>
          {tags.map((tag) => (
            <div
              key={tag.id}
              style={{
                padding: "16px",
                backgroundColor: "#fff",
                border: "1px solid #e0e0e0",
                borderRadius: "8px",
                boxShadow: "0 1px 3px rgba(0,0,0,0.1)",
                transition: "box-shadow 0.2s",
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.boxShadow = "0 4px 8px rgba(0,0,0,0.15)";
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.boxShadow = "0 1px 3px rgba(0,0,0,0.1)";
              }}
            >
              <div style={{ display: "flex", alignItems: "center", gap: "12px", marginBottom: "8px" }}>
                <div
                  style={{
                    width: "24px",
                    height: "24px",
                    borderRadius: "50%",
                    backgroundColor: tag.color,
                    flexShrink: 0,
                    border: "2px solid rgba(0,0,0,0.1)"
                  }}
                />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <h4 style={{
                    margin: 0,
                    fontSize: "16px",
                    fontWeight: "600",
                    overflow: "hidden",
                    textOverflow: "ellipsis",
                    whiteSpace: "nowrap"
                  }}>
                    {tag.name}
                  </h4>
                  <p style={{
                    margin: "2px 0 0 0",
                    fontSize: "12px",
                    color: "#888",
                    fontFamily: "monospace"
                  }}>
                    {tag.color}
                  </p>
                </div>
              </div>

              <div style={{ display: "flex", gap: "8px", marginTop: "12px" }}>
                <button
                  onClick={() => navigate(`/me/tags/${tag.id}/edit`)}
                  className="nav-button secondary"
                  style={{
                    flex: 1,
                    padding: "6px 12px",
                    fontSize: "13px"
                  }}
                >
                  Edit
                </button>
                <button
                  onClick={() => handleDeleteClick(tag.id, tag.name)}
                  disabled={deletingTagId === tag.id}
                  className="nav-button secondary"
                  style={{
                    flex: 1,
                    padding: "6px 12px",
                    fontSize: "13px",
                    backgroundColor: deletingTagId === tag.id ? "#ccc" : undefined,
                    cursor: deletingTagId === tag.id ? "wait" : "pointer"
                  }}
                >
                  {deletingTagId === tag.id ? "Deleting..." : "Delete"}
                </button>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Delete Confirmation Modal */}
      {confirmDelete && (
        <div style={{
          position: "fixed",
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          backgroundColor: "rgba(0, 0, 0, 0.5)",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          zIndex: 1000
        }}>
          <div style={{
            backgroundColor: "#fff",
            padding: "24px",
            borderRadius: "8px",
            maxWidth: "400px",
            width: "90%",
            boxShadow: "0 4px 6px rgba(0, 0, 0, 0.1)"
          }}>
            <h3 style={{ margin: "0 0 16px 0", fontSize: "18px", fontWeight: "600" }}>
              Delete Tag
            </h3>
            <p style={{ margin: "0 0 20px 0", color: "#666" }}>
              Are you sure you want to delete tag "{confirmDelete.tagName}"? This action cannot be undone.
            </p>
            <div style={{ display: "flex", gap: "12px", justifyContent: "flex-end" }}>
              <button
                onClick={handleDeleteCancel}
                className="nav-button secondary"
                style={{ padding: "8px 16px" }}
              >
                Cancel
              </button>
              <button
                onClick={handleDeleteConfirm}
                className="nav-button"
                style={{
                  padding: "8px 16px",
                  backgroundColor: "#dc2626",
                  borderColor: "#dc2626"
                }}
              >
                Delete
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

export default TagsList;
