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

const TagInput = ({
  label = "Tags",
  name = "tags",
  placeholder = "Start typing to add... like employee, manager",
  color = "#e9ecef",
  options = [],
}) => {
  const [tags, setTags] = useState([]);
  const [input, setInput] = useState("");
  const [suggestions, setSuggestions] = useState([]);
  const { setValue, trigger, control } = useFormContext();
  const watchedTags = useWatch({ control, name });


useEffect(() => {
  if (
    Array.isArray(watchedTags) &&
    JSON.stringify(tags) !== JSON.stringify(watchedTags)
  ) {
    setTags(watchedTags);
  }
}, [JSON.stringify(watchedTags)]);

  useEffect(() => {
    if (input.trim() === "") {
      setSuggestions([]);
    } else {
      const filtered = options?.filter(
        (opt) =>
          opt?.name?.toLowerCase()?.includes(input.toLowerCase()) &&
          !tags?.some((tag) => tag.name === opt.name)
      );
      setSuggestions(filtered);
    }
  }, [input, options, tags]);

  const addTag = async (tagObj) => {
    if (!tags.some((tag) => tag.name === tagObj.name)) {
      const cleanedTag = {
        id: tagObj.id ?? null,
        name: tagObj.name,
      };
      const newTags = [...tags, cleanedTag];
      setTags(newTags);
      setValue(name, newTags, { shouldValidate: true });
      await trigger(name);
      setInput("");
      setSuggestions([]);
    }
  };

  const removeTag = (indexToRemove) => {
    const newTags = tags.filter((_, i) => i !== indexToRemove);
    setTags(newTags);
    setValue(name, newTags, { shouldValidate: true });
    trigger(name);
  };

  const handleInputKeyDown = (e) => {
    if ((e.key === "Enter" || e.key === " ")&& input.trim() !== "") {
      e.preventDefault();
      const existing = options.find(
        (opt) => opt.name.toLowerCase() === input.trim().toLowerCase()
      );
      const newTag = existing
        ? existing
        : {
            id: null,
            name: input.trim(),
            description: input.trim(),
          };
      addTag(newTag);
    } else if (e.key === "Backspace" && input === "") {
      setTags((prev) => prev.slice(0, -1));
    }
  };
  const handleInputKey = (e) => {
  const key = e.key?.toLowerCase();

  if ((key === "enter" || key === " " || e.code === "Space") && input.trim() !== "") {
    e.preventDefault();
    const existing = options.find(
      (opt) => opt.name.toLowerCase() === input.trim().toLowerCase()
    );
    const newTag = existing
      ? existing
      : {
          id: null,
          name: input.trim(),
          description: input.trim(),
        };
    addTag(newTag);
  } else if ((key === "backspace" || e.code === "Backspace") && input === "") {
    setTags((prev) => prev.slice(0, -1));
  }
};


  const handleSuggestionClick = (suggestion) => {
    addTag(suggestion);
  };

  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 p-1"
        style={{ minHeight: "38px", position: "relative" }}
      >
        <div className="d-flex flex-wrap align-items-center gap-1">
          {tags.map((tag, index) => (
            <span
              key={index}
              className="d-flex align-items-center"
              style={{
                color: iconColor,
                backgroundColor,
                padding: "2px 6px",
                borderRadius: "2px",
                fontSize: "0.85rem",
              }}
            >
              {tag.name}
              <i
                className="bx bx-x bx-xs ms-1"
                onClick={() => removeTag(index)}
                style={{ cursor: "pointer" }}
              />
            </span>
          ))}

          <input
            type="text"
            value={input}
            onChange={(e) => setInput(e.target.value)}
            onKeyDown={handleInputKeyDown}
              onKeyUp={handleInputKey}
            placeholder={placeholder}
            style={{
              border: "none",
              outline: "none",
              flex: 1,
              minWidth: "120px",
            }}
          />
        </div>

        {suggestions.length > 0 && (
          <ul
            className="list-group position-absolute mt-1 bg-white w-50 shadow-sm "
            style={{
              zIndex: 1000,
              maxHeight: "150px",
              overflowY: "auto",
              boxShadow:"0px 4px 10px rgba(0, 0, 0, 0.2)",borderRadius:"3px",border:"1px solid #ddd"
            }}
          >
            {suggestions.map((sugg, i) => (
              <li
                key={i}
                className="dropdown-item p-1 hoverBox"
                onClick={() => handleSuggestionClick(sugg)}
                style={{cursor: "pointer", fontSize: "0.875rem"}}
                
              >
                {sugg.name}
              </li>
            ))}
          </ul>
        )}
      </div>
    </>
  );
};
export default TagInput;
