'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';

type SettingsData = {
  group: string;
};

export default function Page() {
  const { data: me } = useContext(UserContext);
  const { mutate } = useSWRConfig();
  const { register, handleSubmit } = useForm<SettingsData>({
    defaultValues: {
      group: ''
    }
  });

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

  async function onSubmit(data: SettingsData) {
    const formData = new FormData();

    formData.append('group', data.group);

    const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/groupQuit`, {
      method: 'POST',
      body: formData,
      headers: {
        Authorization: `Bearer ${cookies.get('token')}}`
      }
    });

    if (res.ok) {
      mutate('me');
    }
  }

  return (
    <section className="flex h-full w-full flex-col space-y-4">
      <form className="flex items-center space-x-2" onSubmit={handleSubmit(onSubmit)}>
        <Select {...register('group')} className="w-1/4" options={groups} />
        <Button kind="brand" type="submit">
          Quitter
        </Button>
      </form>
    </section>
  );
}
