'use client'

import type {FunctionComponent} from 'react'
import {useActionState} from 'react'
import PageTitle from '@/components/custom/pageTitle'
import {Button} from '@/components/ui/button'
import {cn} from '@/lib/utils'
import {Label} from '@/components/ui/label'
import {Input} from '@/components/ui/input'
import SubmitButtonWithLoading from '@/components/custom/submitButtonWithLoading'
import Link from 'next/link'
import {registerAction, signInAction} from '@/serverFunctions/users'

interface LoginFormProps {
  register: boolean
}

const LoginForm: FunctionComponent<LoginFormProps> = ({register}) => {
  const [_, signInOrRegister] = useActionState(register ? registerAction : signInAction, undefined)

  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 action={signInOrRegister} className="mt-4 flex flex-col gap-4">
        <div className="flex flex-col gap-2">
          <Label htmlFor="email">Email address</Label>
          <Input type="email" id="email" name="email" placeholder="Email" required />
        </div>

        {register && (
          <div className="flex flex-col gap-2">
            <Label htmlFor="username">Username</Label>
            <Input type="text" id="username" name="username" required placeholder="Username" />
          </div>
        )}

        <div className="flex flex-col gap-2">
          <Label htmlFor="password">Password</Label>
          <Input type="password" id="password" name="password" placeholder="Password" />
        </div>

        {register && (
          <div className="flex flex-col gap-2">
            <Label htmlFor="passwordConfirmation">Confirm your password</Label>
            <Input type="password" id="passwordConfirmation" placeholder="Confirm you password" required />
          </div>
        )}

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

export default LoginForm
