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,
  parent_index,
}: {
  data: any;
  index: number;
  parent_index: number;
}) => {
  const inputRef = useRef<HTMLInputElement>(null);
  const timeoutRef = useRef<NodeJS.Timeout | null>(null);
  const DEBOUNCE_DELAY = 500;
  const formik = useFormikContext<any>();
  const { setTagsSearch, setCurrentTag, setCurrentParentIndex } =
    useObjectToEdit();
  console.log(formik?.values?.Questions);

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

  const handleEditInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    // console.log(e.target.value);

    formik.setFieldValue(`Questions.[${parent_index}].tags[${index}]`, {
      key: parent_index,
      name: e.target.value,
      id: `${parent_index}_key`,
    });
    setCurrentTag(index);
    setCurrentParentIndex(parent_index);
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
    }

    timeoutRef.current = setTimeout(() => {
      setTagsSearch(e.target.value);
    }, DEBOUNCE_DELAY);
  };

  const handleDeleteChoice = () => {
    console.log(data);

    // Create a copy of current tags array
    const currentTags = [...formik.values.tags];

    // 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(`Questions.[${parent_index}].tags`, currentTags);

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

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

export default Tag;
