'use client'

import type {FunctionComponent} from 'react'
import PageTitle from '@/components/custom/pageTitle'
import {Button} from '@/components/ui/button'
import {cn} from '@/lib/utils'
import SubmitButtonWithLoading from '@/components/custom/submitButtonWithLoading'
import Link from 'next/link'
import {registerAction, signInAction} from '@/serverFunctions/users'
import {useZodValidatedForm} from '@/lib/useZodValidatedForm'
import {registerSchema, signInSchema} from '@/schemas/userSchemas'
import Form from '@/components/custom/form'
import FormInput from '@/components/custom/formInput'

interface LoginFormProps {
  register: boolean
}

const LoginForm: FunctionComponent<LoginFormProps> = ({register}) => {
  const [form, signInOrRegister] = useZodValidatedForm(
    register ? registerSchema : signInSchema,
    register ? registerAction : signInAction,
  )

  return (
    <div className="flex flex-col justify-center">
      <div className="mb-4">
        <PageTitle>My contacts</PageTitle>
        <p>Log in to your existing account or create a new one with a real or fake email-address.</p>
      </div>

      <div className="flex flex-row justify-between mb-4">
        <Link href="/login">
          <Button variant="link" className={cn('p-0 text-xl', {underline: !register})}>
            Sign in
          </Button>
        </Link>
        <Link href="/register">
          <Button variant="link" className={cn('p-0 text-xl', {underline: register})}>
            Sign up
          </Button>
        </Link>
      </div>

      <Form hookForm={form} action={signInOrRegister}>
        <FormInput name="email" label="Email address" />

        {register && <FormInput name="username" label="Username" />}

        <FormInput name="password" label="Password" type="password" />

        {register && <FormInput name="passwordConfirmation" label="Confirm your password" type="password" />}

        <SubmitButtonWithLoading
          loadingText={register ? 'Creating your account...' : 'Logging in ...'}
          text={register ? 'Sign up' : 'Log in'}
        />
      </Form>
    </div>
  )
}

export default LoginForm
