import React, { useState, useEffect } from "react";
import { useFormContext } from "react-hook-form";

const TagInput = ({
  label = "Tags",
  name = "tags",
  placeholder = "Enter ... ",
  color = "#e9ecef",
}) => {
  const [tags, setTags] = useState([]);
  const [input, setInput] = useState("");
  const { setValue } = useFormContext();

  useEffect(() => {
    setValue(name, tags); // sync to form when tags change
  }, [tags, name, setValue]);

  const addTag = (e) => {
    e.preventDefault();
    const trimmed = input.trim();
    if (trimmed !== "" && !tags.includes(trimmed)) {
      setTags([...tags, trimmed]);
      setInput("");
    }
  };

  const removeTag = (removeIndex) => {
    const updated = tags.filter((_, i) => i !== removeIndex);
    setTags(updated);
  };

  const backgroundColor = color || "#f8f9fa";
  const iconColor = `var(--bs-${color})`;

  return (
    <>
      <label htmlFor={name} className="form-label">{label}</label>
      <div className="form-control form-control-sm d-flex justify-content-start flex-wrap gap-1" style={{ minHeight: "12px" }}>
        {tags.map((tag, i) => (
          <span
            key={i}
            className="d-flex align-items-center"
            style={{
              color: iconColor,
              backgroundColor,
              padding: "2px 3px",
              borderRadius: "2px"
            }}
          >
            {tag}
            <i className="bx bx-x bx-xs ms-1" onClick={() => removeTag(i)}></i>
          </span>
        ))}
        <input
          type="text"
          className="border-0 flex-grow-1"
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyDown={(e) => (e.key === "Enter" ? addTag(e) : null)}
          placeholder={placeholder}
          style={{ outline: "none", minWidth: "120px" }}
        />
      </div>
    </>
  );
};

export default TagInput;
