'use client';

import cookies from 'js-cookie';
import { useRouter } from 'next/navigation';
import { useContext, useState } from 'react';
import { useForm } from 'react-hook-form';
import { useSWRConfig } from 'swr';
import { z } from 'zod';

import { Button } from '@/components/ui/Button';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage
} from '@/components/ui/Form';
import { Input } from '@/components/ui/Input';
import { UserContext } from '@/context/user';
import { type Player } from '@/lib/players';
import { zodResolver } from '@hookform/resolvers/zod';
import { Loader2 } from 'lucide-react';

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 w-full flex-col space-y-4">
      <header>
        <h1 className="text-xl font-semibold">Mon profil</h1>
        <p className="text-highlight-secondary">
          C&apos;est ici que vous pouvez modifier votre profil.
        </p>
      </header>
      <main className="flex-col space-y-4">
        {me && <ProfileForm user={me!} />}
        {/* {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 type="submit">Quitter</Button>
          </form>
        ) : (
          <p>Vous n&apos; êtes dans aucun groupe</p>
        )} */}
      </main>
    </section>
  );
}

const ProfileFormSchema = z.object({
  email: z.string().email({ message: "L'email doit être valide" }),
  pseudo: z.string(),
  firstname: z.string(),
  lastname: z.string(),
  description: z.string()
});

function ProfileForm({ user }: { user: Player }) {
  const form = useForm<z.infer<typeof ProfileFormSchema>>({
    resolver: zodResolver(ProfileFormSchema),
    defaultValues: {
      email: user.email,
      pseudo: user.pseudo,
      firstname: user.firstname,
      lastname: user.lastname,
      description: user.description
    },
    mode: 'onChange'
  });

  const [submit, setSubmit] = useState(false);

  // TODO: Route pas encore faite
  async function onSubmit(data: z.infer<typeof ProfileFormSchema>) {
    console.log(data);
    setSubmit(!submit);
    setTimeout(() => {
      setSubmit(false);
    }, 2000);
  }

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
        <FormField
          control={form.control}
          name="email"
          render={({ field }) => (
            <FormItem>
              <FormLabel htmlFor="email">Email</FormLabel>
              <FormControl>
                <Input {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name="pseudo"
          render={({ field }) => (
            <FormItem>
              <FormLabel htmlFor="pseudo">Pseudo</FormLabel>
              <FormControl>
                <Input {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name="firstname"
          render={({ field }) => (
            <FormItem>
              <FormLabel htmlFor="firstname">Prénom</FormLabel>
              <FormControl>
                <Input {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name="lastname"
          render={({ field }) => (
            <FormItem>
              <FormLabel htmlFor="lastname">Nom</FormLabel>
              <FormControl>
                <Input {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name="description"
          render={({ field }) => (
            <FormItem>
              <FormLabel htmlFor="description">Description</FormLabel>
              <FormControl>
                <Input {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <Button disabled={submit} variant="brand">
          {submit && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
          Modifier
        </Button>
      </form>
    </Form>
  );
}
