'use client';

import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { useAppForm } from '@/components/ui/tanstack-form';
import { cn } from '@/lib/utils';
import { signIn } from 'next-auth/react';
import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { useTransition } from 'react';
import { toast } from 'sonner';
import * as z from 'zod';
import { InteractiveGridPattern } from './interactive-grid';

const signInSchema = z.object({
  identifier: z.string().trim().min(3, 'Enter your username or email'),
  password: z.string().min(8, 'Password must be at least 8 characters')
});

function getSignInErrorMessage(error?: string | null) {
  if (!error) {
    return 'Unable to sign in';
  }

  if (error === 'CredentialsSignin') {
    return 'Invalid username, email, or password';
  }

  if (error === 'Configuration') {
    return 'Authentication is misconfigured. Please check the server settings.';
  }

  return `Sign-in failed: ${error}`;
}

export default function SignInViewPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const callbackUrl = searchParams.get('callbackUrl') ?? '/dashboard';
  const signInReason = searchParams.get('reason');
  const [isPending, startTransition] = useTransition();

  const form = useAppForm({
    defaultValues: {
      identifier: '',
      password: ''
    },
    validators: {
      onSubmit: signInSchema
    },
    onSubmit: ({ value }) => {
      startTransition(async () => {
        const result = await signIn('credentials', {
          identifier: value.identifier.trim().toLowerCase(),
          password: value.password,
          callbackUrl,
          redirect: false
        });

        if (result?.error) {
          toast.error(getSignInErrorMessage(result.error));
          return;
        }

        toast.success('Signed in successfully');
        router.push(result?.url ?? callbackUrl);
        router.refresh();
      });
    }
  });

  return (
    <div className='relative flex min-h-screen flex-col items-center justify-center overflow-hidden md:grid lg:max-w-none lg:grid-cols-2 lg:px-0'>
      <div className='relative hidden h-full flex-col p-10 lg:flex dark:border-r'>
        <div className='absolute inset-0 bg-sidebar' />
        <div className='text-sidebar-foreground relative z-20 flex items-center text-lg font-medium'>
          <svg
            xmlns='http://www.w3.org/2000/svg'
            viewBox='0 0 24 24'
            fill='none'
            stroke='currentColor'
            strokeWidth='2'
            strokeLinecap='round'
            strokeLinejoin='round'
            className='mr-2 h-6 w-6'
          >
            <path d='M15 6v12a3 3 0 1 0 3-3H6a3 3 0 1 0 3 3V6a3 3 0 1 0-3 3h12a3 3 0 1 0-3-3' />
          </svg>
          Training System Login
        </div>
        <InteractiveGridPattern
          className={cn(
            'mask-[radial-gradient(400px_circle_at_center,white,transparent)]',
            'inset-x-0 inset-y-[0%] h-full skew-y-12'
          )}
        />
        <div className='text-sidebar-foreground relative z-20 mt-auto'>
          <blockquote className='space-y-2'>
            <p className='text-lg'>
              &ldquo;Move from template scaffolding to app-owned auth and data without tearing up
              the dashboard UX.&rdquo;
            </p>
            <footer className='text-sidebar-foreground/70 text-sm'>Training System</footer>
          </blockquote>
        </div>
      </div>
      <div className='flex h-full items-center justify-center p-4 lg:p-8'>
        <div className='flex w-full max-w-md flex-col items-center justify-center space-y-6'>
          <div className='w-full space-y-2 text-center'>
            <h1 className='text-2xl font-semibold tracking-tight'>Sign in to your organizer</h1>
            <p className='text-muted-foreground text-sm'>
              Use the credentials created for you by a super admin or organizer admin.
            </p>
            {signInReason === 'session-expired' ? (
              <p className='text-destructive text-sm'>
                เซสชันหมดอายุเนื่องจากไม่มีการใช้งานเกิน 5 นาที กรุณาเข้าสู่ระบบอีกครั้ง
              </p>
            ) : null}
          </div>

          <form.AppForm>
            <form.Form className='w-full space-y-4'>
              <form.AppField
                name='identifier'
                children={(field) => (
                  <field.FieldSet>
                    <field.Field>
                      <field.FieldLabel htmlFor={field.name}>Username or Email</field.FieldLabel>
                      <Input
                        id={field.name}
                        name={field.name}
                        type='text'
                        value={field.state.value}
                        onBlur={field.handleBlur}
                        onChange={(event) => field.handleChange(event.target.value)}
                        placeholder='hrd.admin or you@example.com'
                        disabled={isPending}
                      />
                    </field.Field>
                    <field.FieldError />
                  </field.FieldSet>
                )}
              />

              <form.AppField
                name='password'
                children={(field) => (
                  <field.FieldSet>
                    <field.Field>
                      <field.FieldLabel htmlFor={field.name}>Password</field.FieldLabel>
                      <Input
                        id={field.name}
                        name={field.name}
                        type='password'
                        value={field.state.value}
                        onBlur={field.handleBlur}
                        onChange={(event) => field.handleChange(event.target.value)}
                        placeholder='Enter your password'
                        disabled={isPending}
                      />
                    </field.Field>
                    <field.FieldError />
                  </field.FieldSet>
                )}
              />

              <Button className='w-full' type='submit' isLoading={isPending}>
                Sign in
              </Button>
            </form.Form>
          </form.AppForm>

          <div className='text-muted-foreground space-y-2 px-8 text-center text-xs'>
            <p>
              Self-service sign-up is disabled. Ask an administrator to create your account if you
              do not have one yet.
            </p>
            <p>
              <Link
                href='https://github.com/kiranism/next-shadcn-dashboard-starter'
                target='_blank'
                className='hover:text-primary underline underline-offset-4'
              >
                View the original starter
              </Link>
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}
