import { useFormikContext } from "formik";
import React, { useRef, useEffect } from "react";
import { useObjectToEdit } from "../../../zustand/ObjectToEditState";
import { FaTrash } from "react-icons/fa";

const Tag = ({ data, index }: { data: any; index: number }) => {
  const inputRef = useRef<HTMLInputElement>(null);
  const formik = useFormikContext<any>();
  const { setTagsSearch, setCurrentTag } = useObjectToEdit();

  useEffect(() => {
    if (inputRef.current) {
      inputRef.current.style.width = `${(formik?.values?.synonyms[index]?.length + 1) * 8}px`;
    }
  }, [formik?.values?.synonyms[index]]);
  console.log(formik?.values?.synonyms);
  console.log(index);

  const handleEditInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    // console.log(e.target.value);
    formik.setFieldValue(`synonyms[${index}]`, e.target.value);
    setTagsSearch(e.target.value);
    setCurrentTag(index);
  };

  const handleInputBlur = () => {
    // setTagsSearch(null)
  };

  const handleDeleteChoice = () => {
    console.log(data);
    // Create a copy of current tags array
    const currentTags = [...formik.values.synonyms];
    // Remove the item at the specified index from the array
    currentTags.splice(index, 1);
    console.log(currentTags); // Log the updated tags array

    // Update formik field value with the updated tags array
    formik.setFieldValue("synonyms", currentTags);

    // Reset search state if needed
    setTagsSearch(null);
  };

  return (
    <div className="tag">
      <input
        ref={inputRef}
        className="tagInput"
        type="text"
        value={formik?.values?.synonyms[index]}
        onChange={handleEditInputChange}
        onBlur={handleInputBlur}
      />
      <FaTrash onClick={handleDeleteChoice} />
    </div>
  );
};

export default Tag;
