'use client';

import { useState, useTransition } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { Loader2 } 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 {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
  CardFooter
} from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { signIn } from '@/lib/auth/auth-client';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormMessage
} from '@/components/ui/form';
import { Routes } from '@/config/routes';
import { toast } from 'sonner';
import Image from 'next/image';

function useSchema() {
  return z.object({
    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' }),
    rememberMe: z.boolean().optional()
  });
}

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

type Props = {
  callbackURL?: string;
};

export default function SignIn({ callbackURL }: Props) {
  const [loading, startTransition] = useTransition();
  const [showPassword, setShowPassword] = useState(false);
  const router = useRouter();
  const schema = useSchema();

  const form = useForm<SignInFormData>({
    resolver: zodResolver(schema),
    defaultValues: {
      email: '',
      password: '',
      rememberMe: false
    }
  });

  const onSubmit = (data: SignInFormData) => {
    startTransition(async () => {
      await signIn.email(
        { ...data },
        {
          onSuccess() {
            router.push(callbackURL || Routes.HOME);
          },
          onError({ error }) {
            toast.error(error.message);
          }
        }
      );
    });
  };

  return (
    <Card className='w-full gap-8 rounded-none border-0 shadow-none'>
      <CardHeader className='gap-0'>
        <Link href={Routes.HOME}>
          <Image
            src='/logo.svg'
            alt='Magasinet KBH'
            width={120}
            height={120}
            className='size-[80px] md:size-[120px]'
            priority
          />
        </Link>

        <CardTitle className='mt-6 text-2xl font-bold md:text-4xl'>
          Log ind
        </CardTitle>
        <CardDescription className='mt-0.5 font-serif text-sm leading-[1.2] text-[#303030] md:text-lg'>
          — og vær med til at skabe København
        </CardDescription>
      </CardHeader>
      <CardContent>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)}>
            {/* Email */}

            <FormField
              control={form.control}
              name='email'
              render={({ field }) => (
                <FormItem>
                  <FormControl>
                    <Input
                      id='email'
                      type='email'
                      autoComplete='email'
                      placeholder='Email / brugernavn'
                      className='border-dark-gray px-4 shadow-none md:h-17 md:text-xl'
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* Password */}

            <FormField
              control={form.control}
              name='password'
              render={({ field }) => (
                <FormItem>
                  <div className='relative mt-8'>
                    <FormControl>
                      <Input
                        className='border-dark-gray pr-12 pl-4 shadow-none md:h-17 md:text-xl'
                        id='password'
                        type={showPassword ? 'text' : 'password'}
                        autoComplete='current-password'
                        placeholder='Kodeord'
                        {...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 ? (
                        <svg
                          xmlns='http://www.w3.org/2000/svg'
                          viewBox='0 0 640 640'
                          className='size-6'
                        >
                          <path d='M73 39.1C63.6 29.7 48.4 29.7 39.1 39.1C29.8 48.5 29.7 63.7 39 73.1L567 601.1C576.4 610.5 591.6 610.5 600.9 601.1C610.2 591.7 610.3 576.5 600.9 567.2L504.5 470.8C507.2 468.4 509.9 466 512.5 463.6C559.3 420.1 590.6 368.2 605.5 332.5C608.8 324.6 608.8 315.8 605.5 307.9C590.6 272.2 559.3 220.2 512.5 176.8C465.4 133.1 400.7 96.2 319.9 96.2C263.1 96.2 214.3 114.4 173.9 140.4L73 39.1zM236.5 202.7C260 185.9 288.9 176 320 176C399.5 176 464 240.5 464 320C464 351.1 454.1 379.9 437.3 403.5L402.6 368.8C415.3 347.4 419.6 321.1 412.7 295.1C399 243.9 346.3 213.5 295.1 227.2C286.5 229.5 278.4 232.9 271.1 237.2L236.4 202.5zM357.3 459.1C345.4 462.3 332.9 464 320 464C240.5 464 176 399.5 176 320C176 307.1 177.7 294.6 180.9 282.7L101.4 203.2C68.8 240 46.4 279 34.5 307.7C31.2 315.6 31.2 324.4 34.5 332.3C49.4 368 80.7 420 127.5 463.4C174.6 507.1 239.3 544 320.1 544C357.4 544 391.3 536.1 421.6 523.4L357.4 459.2z' />
                        </svg>
                      ) : (
                        <svg
                          xmlns='http://www.w3.org/2000/svg'
                          viewBox='0 0 640 640'
                          className='size-6'
                        >
                          <path d='M320 96C239.2 96 174.5 132.8 127.4 176.6C80.6 220.1 49.3 272 34.4 307.7C31.1 315.6 31.1 324.4 34.4 332.3C49.3 368 80.6 420 127.4 463.4C174.5 507.1 239.2 544 320 544C400.8 544 465.5 507.2 512.6 463.4C559.4 419.9 590.7 368 605.6 332.3C608.9 324.4 608.9 315.6 605.6 307.7C590.7 272 559.4 220 512.6 176.6C465.5 132.9 400.8 96 320 96zM176 320C176 240.5 240.5 176 320 176C399.5 176 464 240.5 464 320C464 399.5 399.5 464 320 464C240.5 464 176 399.5 176 320zM320 256C320 291.3 291.3 320 256 320C244.5 320 233.7 317 224.3 311.6C223.3 322.5 224.2 333.7 227.2 344.8C240.9 396 293.6 426.4 344.8 412.7C396 399 426.4 346.3 412.7 295.1C400.5 249.4 357.2 220.3 311.6 224.3C316.9 233.6 320 244.4 320 256z' />
                        </svg>
                      )}
                    </Button>
                  </div>

                  <FormMessage />
                </FormItem>
              )}
            />
            <Link
              href={Routes.AUTH.FORGOT_PASSWORD}
              className='text-client-red mt-4 inline-block font-serif hover:underline md:text-lg'
            >
              Glemt kodeord?
            </Link>
            <Button
              type='submit'
              className='mt-10 w-full bg-neutral-900 font-medium md:h-17 md:text-3xl'
              disabled={loading}
            >
              {loading ? (
                <Loader2 className='animate-spin md:size-10' />
              ) : (
                'Log ind'
              )}
            </Button>
          </form>
        </Form>
        <span className='my-4 block text-center font-serif md:my-7 md:text-lg'>
          Eller log ind med
        </span>
        <div className='flex flex-col gap-2 md:gap-4'>
          <Button
            className='relative w-full bg-[#3B5998] font-medium text-white hover:bg-[#5875b2] md:h-17 md:text-3xl'
            onClick={async () => {
              await signIn.social({
                provider: 'facebook',
                callbackURL: Routes.HOME
              });
            }}
          >
            <Image
              src='/icons/facebook_icon_white.svg'
              alt='Facebook icon'
              width={20}
              height={20}
              className='absolute left-4 h-6 w-6 md:h-10 md:w-10'
            />
            <span>Facebook</span>
          </Button>
          <Button
            className='relative w-full bg-[#EA4335] font-medium text-white hover:bg-red-400 md:h-17 md:text-3xl'
            onClick={async () => {
              await signIn.social({
                provider: 'google',
                callbackURL: Routes.HOME
              });
            }}
          >
            <Image
              src='/icons/google_icon_white.svg'
              alt='Google icon'
              width={20}
              height={20}
              className='absolute left-4 h-6 w-6 md:h-10 md:w-10'
            />
            <span>Google</span>
          </Button>
        </div>
      </CardContent>

      <CardFooter>
        <p className='w-full text-center font-serif md:text-lg'>
          Har du endnu ikke en profil?{' '}
          <Link
            href={Routes.AUTH.SIGN_UP}
            className='text-client-red block hover:underline'
          >
            Opret ny profil
          </Link>
        </p>
      </CardFooter>
    </Card>
  );
}
