import { createFileRoute, Link, useNavigate } from '@tanstack/react-router'
import { Alert, Anchor, Button, PasswordInput, Stack, Text, TextInput } from '@pikku/mantine/core'
import { useState } from 'react'
import { m } from '@/i18n/messages'
import { useLocale } from '@/i18n/config'
import { asI18n } from '@pikku/react'
import { useMutation } from '@tanstack/react-query'
import { AuthLayout } from '../auth/AuthLayout'
import { registerWithPassword, signInWithPassword, EMAIL_IN_USE } from '../lib/auth'

function SignupPage() {
  useLocale()
  const navigate = useNavigate()
  const [displayName, setDisplayName] = useState('')
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')

  const signup = useMutation({
    mutationFn: async () => {
      await registerWithPassword(email.trim(), password, displayName.trim())
      await signInWithPassword(email.trim(), password)
    },
    onSuccess: () => navigate({ to: '/companies' }),
  })

  const errorMsg = signup.error instanceof Error
    ? signup.error.message === EMAIL_IN_USE
      ? m.auth_signup_errors_email_taken()
      : asI18n(signup.error.message)
    : null

  return (
    <AuthLayout
      title={m.auth_signup_title()}
      subtitle={m.auth_signup_subtitle()}
      tagline={m.app_tagline()}
      footer={
        <>
          {m.auth_signup_have_account()}{' '}
          <Anchor component={Link} to="/login" fw={500}>
            {m.auth_signup_login_cta()}
          </Anchor>
        </>
      }
    >
      <form onSubmit={(e) => { e.preventDefault(); signup.mutate() }}>
        <Stack gap="sm">
          <TextInput
            label={m.auth_signup_display_name()}
            value={displayName}
            onChange={(e) => setDisplayName(e.currentTarget.value)}
            required
            size="md"
            radius="md"
            autoComplete="name"
          />
          <TextInput
            type="email"
            label={m.auth_login_email()}
            placeholder={m.auth_login_email_placeholder()}
            value={email}
            onChange={(e) => setEmail(e.currentTarget.value)}
            required
            size="md"
            radius="md"
            autoComplete="email"
          />
          <PasswordInput
            label={m.auth_login_password()}
            description={m.auth_signup_password_hint()}
            value={password}
            onChange={(e) => setPassword(e.currentTarget.value)}
            required
            minLength={8}
            size="md"
            radius="md"
            autoComplete="new-password"
          />
          {errorMsg && (
            <Alert color="red" variant="light">
              <Text size="sm">{errorMsg}</Text>
            </Alert>
          )}
          <Button type="submit" loading={signup.isPending} fullWidth size="md" radius="md">
            {m.auth_signup_submit()}
          </Button>
        </Stack>
      </form>
    </AuthLayout>
  )
}

export const Route = createFileRoute('/signup')({
  component: SignupPage,
})
