import {
  Box,
  Button,
  FormControl,
  FormLabel,
  Stack,
  SimpleGrid,
  Input,
  Switch,
} from "@chakra-ui/react";
import CardTeam from "Components/Cards/Team";
import { AnimatePresence, motion } from "framer-motion";
import useTeamGenerator from "lib/Hooks/useTeamGenerator";
import { useEffect } from "react";
import { useFieldArray, useForm } from "react-hook-form";
import PlayerNameInput from "./Input";

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

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

  const { teams, players, setConfig, setPlayers, generate, set, save } =
    useTeamGenerator();

  useEffect(() => {
    if (players.length > 0) {
      remove(0);
      players.map((name) => append({ value: name }));
    }
  }, []);

  return (
    <Box>
      <form
        onSubmit={handleSubmit((values) => {
          setConfig({ teamCount: values.teamCount });
          setPlayers(values.players.map((player) => player.value));
          generate();
        })}
      >
        <Stack mb={6} spacing={3}>
          <FormControl>
            <FormLabel htmlFor="team-count">Player names</FormLabel>
            <Stack spacing={3}>
              <AnimatePresence>
                {fields.map((field, index) => (
                  <PlayerNameInput
                    register={register}
                    fieldsLength={fields.length}
                    getValues={getValues}
                    index={index}
                    onAppend={() => append({ value: "" })}
                    onRemove={() => remove(index)}
                    key={field.id}
                  />
                ))}
              </AnimatePresence>
            </Stack>
          </FormControl>
        </Stack>

        <Stack spacing={6}>
          <FormControl>
            <FormLabel htmlFor="team-count">Team count</FormLabel>
            <Input
              id="team-count"
              placeholder="Team Count"
              type="number"
              {...register(`teamCount`, { valueAsNumber: true })}
              defaultValue={2}
            />
          </FormControl>
          <FormControl>
            <FormLabel htmlFor="save-players">Save players?</FormLabel>
            <Switch
              defaultChecked={save}
              onChange={(e) => {
                set({ save: e.target.checked });
              }}
            />
          </FormControl>
          <Button type="submit">Generate</Button>
        </Stack>
      </form>

      {teams.length > 0 && (
        <SimpleGrid
          variants={{
            enter: { transition: { staggerChildren: 0.2 } },
            from: {},
          }}
          as={motion.div}
          columns={2}
          animate="enter"
          initial="from"
          mt="2.5rem"
          spacing="1.5rem"
        >
          {teams.map((team, index) => (
            <CardTeam players={team} index={index} key={index} />
          ))}
        </SimpleGrid>
      )}
    </Box>
  );
};

export default SectionTeamGenerator;
