'use client';

import { useState, useTransition } from 'react';
import { usePathname, useSearchParams } from 'next/navigation';
import { Loader2, Eye, EyeOff } from 'lucide-react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormMessage
} from '@/components/ui/form';
import { signUp } from '@/lib/auth/auth-client';
import { signIn } from '@/lib/auth/auth-client';
import { toast } from 'sonner';
import Image from 'next/image';

function useSchema() {
  return z.object({
    firstName: z.string().min(1, { message: 'Dette felt er påkrævet' }),
    lastName: z.string().min(1, { message: 'Dette felt er påkrævet' }),
    email: z
      .string()
      .min(1, { message: 'Dette felt er påkrævet' })
      .email({ message: 'Indtast en gyldig e-mail' }),
    password: z
      .string()
      .min(6, { message: 'Adgangskoden skal være mindst 6 tegn lang' })
  });
}

type SignUpFormData = z.infer<ReturnType<typeof useSchema>>;

export default function SignUp() {
  const [loading, startTransition] = useTransition();
  const [showPassword, setShowPassword] = useState(false);
  const pathName = usePathname();
  const searchParams = useSearchParams();
  const planName = searchParams.get('plan');
  const schema = useSchema();

  const form = useForm<SignUpFormData>({
    resolver: zodResolver(schema),
    defaultValues: {
      firstName: '',
      lastName: '',
      email: '',
      password: ''
    }
  });

  const onSubmit = (data: SignUpFormData) => {
    startTransition(async () => {
      await signUp.email(
        {
          email: data.email,
          password: data.password,
          name: `${data.firstName} ${data.lastName}`,
          callbackURL: `${pathName}${!planName ? '?plan=' + planName : ''}`
        },
        {
          onError({ error }: { error: { message: string } }) {
            toast.error(error.message);
          }
        }
      );
    });
  };

  return (
    <div>
      <div className='mx-8 flex flex-col gap-4'>
        <Button
          className='relative h-11 rounded-none bg-[#3B5998] px-10 py-2 text-sm font-bold text-white hover:bg-[#5875b2]'
          onClick={async () => {
            await signIn.social({
              provider: 'facebook',
              callbackURL: `${pathName}${!planName ? '?plan=' + planName : ''}`
            });
          }}
        >
          <Image
            src='/icons/facebook_icon_white.svg'
            alt='Facebook icon'
            width={20}
            height={20}
            className='absolute left-3 size-5'
          />
          <span>Facebook</span>
        </Button>
        <Button
          variant='outline'
          className='relative h-11 rounded-none px-10 py-2 text-sm font-bold text-neutral-600 transition'
          onClick={async () => {
            await signIn.social({
              provider: 'google',
              callbackURL: `${pathName}${!planName ? '?plan=' + planName : ''}`
            });
          }}
        >
          <Image
            src='/icons/google_icon.svg'
            alt='Google icon'
            width={20}
            height={20}
            className='absolute left-3 size-5'
          />
          <span>Google</span>
        </Button>
      </div>
      <span className='before:height-1 relative my-2 block text-center text-sm before:absolute before:top-[50%] before:left-0 before:z-0 before:w-full before:border-t before:border-neutral-300'>
        <span className='relative inline-block bg-neutral-100 p-4'>
          Eller opret med
        </span>
      </span>
      <Form {...form}>
        <form
          onSubmit={form.handleSubmit(onSubmit)}
          className='grid gap-4 font-normal'
        >
          <FormField
            control={form.control}
            name='firstName'
            render={({ field }) => (
              <FormItem>
                <FormControl>
                  <Input
                    id='firstName'
                    type='text'
                    placeholder='Fornavn'
                    className='h-11 rounded-none bg-white'
                    {...field}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name='lastName'
            render={({ field }) => (
              <FormItem>
                <FormControl>
                  <Input
                    id='lastName'
                    type='text'
                    placeholder='Efternavn'
                    className='h-11 rounded-none bg-white'
                    {...field}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name='email'
            render={({ field }) => (
              <FormItem>
                <FormControl>
                  <Input
                    id='email'
                    type='email'
                    autoComplete='email'
                    placeholder='Din email adresse'
                    className='h-11 rounded-none bg-white'
                    {...field}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name='password'
            render={({ field }) => (
              <FormItem>
                <div className='relative'>
                  <FormControl>
                    <Input
                      className='h-11 rounded-none bg-white'
                      id='password'
                      type={showPassword ? 'text' : 'password'}
                      autoComplete='current-password'
                      placeholder='Din password'
                      {...field}
                    />
                  </FormControl>
                  <Button
                    type='button'
                    variant='ghost'
                    size='icon'
                    className='absolute top-1/2 right-2 -translate-y-1/2 cursor-pointer hover:bg-transparent'
                    onClick={() => setShowPassword(!showPassword)}
                  >
                    {showPassword ? (
                      <EyeOff className='size-6 text-neutral-700' />
                    ) : (
                      <Eye className='size-6 text-neutral-700' />
                    )}
                  </Button>
                </div>

                <FormMessage />
              </FormItem>
            )}
          />
          <button
            type='submit'
            className='bg-client-red hover:bg-client-red/80 mx-8 mb-4 flex h-11 justify-center px-6 py-2 text-lg font-bold text-white transition'
            disabled={loading}
          >
            {loading ? <Loader2 className='size-6 animate-spin' /> : 'Log ind'}
          </button>
        </form>
      </Form>
    </div>
  );
}
