'use client';

import cookies from 'js-cookie';
import { useContext } from 'react';
import { useForm } from 'react-hook-form';
import { useSWRConfig } from 'swr';

import { UserContext } from '@/context/user';
import Button from '@/ui/Button';
import Select from '@/ui/Select';
import { useRouter } from 'next/navigation';

type SettingsData = {
  name: string;
  chapter?: number;
  puzzle?: number;
};

export default function Page() {
  const { data: me } = useContext(UserContext);
  const { mutate } = useSWRConfig();
  const router = useRouter();
  const { register, handleSubmit } = useForm<SettingsData>({
    defaultValues: {
      name: '',
      chapter: undefined,
      puzzle: undefined
    }
  });

  const groups =
    (me?.groups &&
      me?.groups.map((group) => ({
        title: group.name,
        value: group.name
      }))) ||
    [];

  async function onSubmit(data: SettingsData) {
    if (!data) return;

    const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/groupQuit`, {
      method: 'POST',
      body: JSON.stringify({
        name: data.name,
        chapter: me?.groups?.find((group) => group.name === data.name)?.chapter
        // puzzle: me?.groups?.find((group) => group.name === data.name)?.puzzle
      }),
      headers: {
        Authorization: `Bearer ${cookies.get('token')}}`
      }
    });

    if (res.ok) {
      mutate('me');
      router.push('/dashboard/puzzles');
    } else if (res.status === 423) {
      alert("Vous ne pouvez pas quitter un groupe en cours d'évenement");
    }
  }

  return (
    <section className="flex h-full w-full flex-col space-y-4">
      {me && me?.groups?.length > 0 ? (
        <form className="flex w-1/4 flex-col space-y-2" onSubmit={handleSubmit(onSubmit)}>
          <Select label="Quitter un groupe" {...register('name')} options={groups} />
          <Button kind="brand" type="submit">
            Quitter
          </Button>
        </form>
      ) : (
        <p>Vous n&apos; êtes dans aucun groupe</p>
      )}
    </section>
  );
}
