'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 = {
  name: string;
};

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

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

  async function onSubmit(data: SettingsData) {
    const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/groupQuit`, {
      method: 'POST',
      body: JSON.stringify(data),
      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('name')} className="w-1/4" options={groups} />
        <Button kind="brand" type="submit">
          Quitter
        </Button>
      </form>
    </section>
  );
}
