import { useState } from "react";

export const useTagManager = (initialTags: string[] = []) => {
  const [tagInput, setTagInput] = useState("");
  const [tags, setTags] = useState<string[]>(initialTags);

  const addTag = () => {
    const trimmedTag = tagInput.trim();
    if (trimmedTag && !tags.includes(trimmedTag)) {
      setTags((prev) => [...prev, trimmedTag]);
      setTagInput("");
    }
  };

  const removeTag = (tagToRemove: string) => {
    setTags((prev) => prev.filter((tag) => tag !== tagToRemove));
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter") {
      e.preventDefault();
      addTag();
    }
  };

  const setTagsValue = (newTags: string[]) => {
    setTags(newTags);
  };

  return {
    tagInput,
    setTagInput,
    tags,
    addTag,
    removeTag,
    handleKeyDown,
    setTags: setTagsValue,
  };
};
