import { CloseIcon } from "@chakra-ui/icons";
import { Button, Input, InputGroup, InputRightElement } from "@chakra-ui/react";
import { ease } from "@unom/style";
import { m } from "framer-motion";
import { VFC } from "react";
import type { UseFormGetValues, UseFormRegister } from "react-hook-form";

const PlayerNameInput: VFC<{
  index: number;
  onRemove: () => void;
  onAppend: () => void;
  fieldsLength: number;
  getValues: UseFormGetValues<any>;
  register: UseFormRegister<any>;
}> = ({ index, onRemove, onAppend, register, fieldsLength, getValues }) => {
  return (
    <InputGroup
      as={m.div}
      exit="exit"
      animate="enter"
      initial="from"
      variants={{
        enter: {
          scale: 1,
          transition: ease.quint(0.8).out,
        },
        from: {
          scale: 0,
        },
        exit: {
          scale: 0,
          transition: {
            type: "tween",
            ease: "circIn",
            duration: 0.2,
          },
        },
      }}
      transition="none"
    >
      {index !== 0 && (
        <InputRightElement>
          <Button mr="0.25rem" size="sm" onClick={() => onRemove()}>
            <CloseIcon />
          </Button>
        </InputRightElement>
      )}
      <Input
        placeholder={`Player ${index + 1} name`}
        size="md"
        type="name"
        {...register(`players.${index}.value`)}
        autoFocus={index === fieldsLength}
        onKeyDown={(e) => {
          if (e.key === "Enter" && index === fieldsLength - 1) {
            e.preventDefault();
            const value = getValues(`players.${index}.value`);
            if (value !== "") {
              onAppend();
            } else if (index !== 0) {
              onRemove();
            }
          }
        }}
      />
    </InputGroup>
  );
};

export default PlayerNameInput;
