import { CloseIcon } from "@chakra-ui/icons";
import {
  Box,
  Button,
  FormControl,
  FormLabel,
  Text,
  Stack,
  SimpleGrid,
  chakra,
  Input,
  InputRightElement,
  InputGroup,
} from "@chakra-ui/react";
import CardTeam from "Components/Cards/Team";
import { AnimatePresence, isValidMotionProp, motion } from "framer-motion";
import { useState } from "react";
import { useFieldArray, useForm } from "react-hook-form";

const getRandom = (list: Array<any>) => {
  return list[Math.floor(Math.random() * list.length)];
};

const SectionTeamGenerator = () => {
  const [teams, setTeams] = useState<Array<Array<string>>>([]);
  const {
    handleSubmit,
    register,
    control,
    getValues,
    formState: { errors, isSubmitting },
  } = useForm({ defaultValues: { players: [{ value: "" }], teamCount: 2 } });

  const { fields, append, remove } = useFieldArray({
    control,
    name: "players",
  });

  return (
    <Box>
      <form
        onSubmit={handleSubmit((values) => {
          const shuffledPlayers = [...values.players]
            .sort(() => (Math.random() > 0.5 ? 1 : -1))
            .map((value) => value.value);

          const teams = [];

          const range = Math.ceil(values.players.length / values.teamCount);
          while (shuffledPlayers.length > 0) {
            teams.push(shuffledPlayers.splice(0, range));
          }

          setTeams(teams);
        })}
      >
        <Stack mb={6} spacing={3}>
          <FormControl>
            <FormLabel htmlFor="team-count">Player names</FormLabel>
            <Stack spacing={3}>
              <AnimatePresence>
                {fields.map((field, index) => (
                  <InputGroup
                    as={motion.div}
                    animate={{
                      scale: 1,
                      transition: {
                        type: "spring",
                        stiffness: 200,
                        damping: 15,
                        mass: 1,
                      },
                    }}
                    transition="none"
                    initial={{ scale: 0 }}
                    exit={{
                      scale: 0,
                      transition: {
                        type: "tween",
                        ease: "circIn",
                        duration: 0.2,
                      },
                    }}
                  >
                    {index !== 0 && (
                      <InputRightElement>
                        <Button
                          mr="0.25rem"
                          size="sm"
                          onClick={() => remove(index)}
                        >
                          <CloseIcon />
                        </Button>
                      </InputRightElement>
                    )}
                    <Input
                      placeholder={`Player ${index + 1} name`}
                      key={field.id}
                      size="md"
                      type="name"
                      {...register(`players.${index}.value`)}
                      autoFocus={index === fields.length}
                      onKeyDown={(e) => {
                        if (e.key === "Enter" && index === fields.length - 1) {
                          e.preventDefault();
                          const value = getValues(`players.${index}.value`);
                          if (value !== "") {
                            append({ value: "" });
                          } else {
                            remove(index);
                          }
                        }
                      }}
                    />
                  </InputGroup>
                ))}
              </AnimatePresence>
            </Stack>
          </FormControl>
        </Stack>
        <Stack spacing={6} as={motion.div} layout>
          <FormControl>
            <FormLabel htmlFor="team-count">Team count</FormLabel>
            <Input
              id="team-count"
              placeholder="Team Count"
              type="number"
              {...register(`teamCount`, { valueAsNumber: true })}
              defaultValue={2}
            />
          </FormControl>
          <Button type="submit">Generate</Button>
        </Stack>
      </form>

      <SimpleGrid as={motion.div} columns={2} mt="1rem" spacing="1.5rem">
        {teams.map((team, index) => (
          <CardTeam players={team} index={index} key={index} />
        ))}
      </SimpleGrid>
    </Box>
  );
};

export default SectionTeamGenerator;
