import { useState, type ChangeEvent, type Dispatch, type FormEvent, type SetStateAction } from "react";

interface RecipeCreateFormTagsInputsProps {
  tags: string[];
  setTags: Dispatch<SetStateAction<string[]>>;
  classes: string;
}

export default function RecipeCreateFormTagsInputs({ tags, setTags, classes }: RecipeCreateFormTagsInputsProps) {
  const [input, setInput] = useState<string>("");

  const changeHandler = (e: ChangeEvent<HTMLInputElement>) => setInput(e.target.value);

  const tagCreationHandler = (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    // why would anyone try this lol
    if (input.trim() === "") return;

    // Tag already exists, clear input and exit
    if (tags.includes(input.toLowerCase())) {
      setInput("");
      return;
    }

    setInput("");
    setTags(prev => [...prev, input.toLowerCase()]);
  }

  const tagDeletionHandler = (tag: string) => {
    if (!tag) return;
    setTags(prev => prev.filter(t => t !== tag));
  }

  return (
    <form onSubmit={tagCreationHandler} className="my-4 flex flex-col gap-x-2">
      <div className="flex flex-col flex-grow">
        <label htmlFor="tags" className="text-sm">
          Recipe Tags
        </label>
        <p className="text-xs pt-1 pb-2 text-gray-700">
          Please provide a list of tags. <span className="italic">e.g., easy, dairy-free, gluten-free, high protein.</span>
        </p>
        <input
          type="text"
          value={input}
          onChange={changeHandler}
          name="tagInput"
          maxLength={32}
          enterKeyHint="done"
          placeholder="e.g., Healthy"
          className={classes}
        />
        <input type="hidden" name="tags" id="tags" value="" />
      </div>
      <ul id="tag-list" className="my-2 flex gap-1 flex-wrap">
        {tags?.map(tag =>
          <li
            className="flex text-xs items-center bg-blue-100 w-fit px-2 py-1 rounded-full gap-x-1 select-none cursor-pointer hover:bg-blue-200 duration-300"
            key={tag}
          >
            <button tabIndex={-1} type="button" onClick={() => tagDeletionHandler(tag)}>
              &times; {tag}
            </button>
          </li>
        )}
      </ul>
    </form>
  );
}
