import { useEffect, useState } from "react";
import { Trash2 } from "lucide-react";

export default function TagsgComponent() {
  const [tags, setTags] = useState<{ id: number; name: string }[]>([]);
  const [globalError, setGlobalError] = useState<string | null>(null);

  useEffect(() => {
    const fetchTags = async () => {
      const res = await fetch(
        `${
          process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001"
        }/api/articles/tags/all`,
        {
          credentials: "include",
        }
      );
      const data = await res.json();
      setTags(data);
    };
    fetchTags();
  }, []);

  const confirmDelete = async (id: number) => {
    try {
      const res = await fetch(
        `${
          process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001"
        }/api/articles/tags/${id}`,
        {
          method: "DELETE",
          credentials: "include",
        }
      );
      if (!res.ok) {
        const err = await res.json();
        throw new Error(err.error || "Erreur lors de la suppression");
      }
      setTags((prev) => prev.filter((tag) => tag.id !== id));
      setGlobalError(null);
    } catch (error: unknown) {
      setGlobalError(
        error instanceof Error ? error.message : "Erreur lors de la suppression"
      );
    }
  };

  return (
    <>
      <h4 className="text-xl font-semibold text-gray-800">Gérer les tags</h4>

      {globalError && (
        <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-2 rounded my-2">
          {globalError}
        </div>
      )}

      {tags.map((tag) => (
        <div
          key={tag.id}
          className="flex items-center space-x-2 gap-4 justify-between"
        >
          <p>{tag.name}</p>
          <button
            type="submit"
            className="mt-2 text-red-600 px-4 py-2 rounded"
            onClick={() => confirmDelete(tag.id)}
          >
            <Trash2 />
          </button>
        </div>
      ))}
    </>
  );
}
