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 { signInWithPassword, INVALID_CREDENTIALS } from '../lib/auth'

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

  const login = useMutation({
    mutationFn: () => signInWithPassword(email.trim(), password),
    onSuccess: () => navigate({ to: '/companies' }),
  })

  const errorMsg = login.error instanceof Error
    ? login.error.message === INVALID_CREDENTIALS
      ? m.auth_login_errors_invalid_credentials()
      : asI18n(login.error.message)
    : null

  return (
    <AuthLayout
      title={m.auth_login_title()}
      subtitle={m.auth_login_subtitle()}
      tagline={m.app_tagline()}
      footer={
        <>
          {m.auth_login_no_account()}{' '}
          <Anchor component={Link} to="/signup" fw={500}>
            {m.auth_login_signup_cta()}
          </Anchor>
        </>
      }
    >
      <form onSubmit={(e) => { e.preventDefault(); login.mutate() }}>
        <Stack gap="sm">
          <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()}
            value={password}
            onChange={(e) => setPassword(e.currentTarget.value)}
            required
            size="md"
            radius="md"
            autoComplete="current-password"
          />
          {errorMsg && (
            <Alert color="red" variant="light">
              <Text size="sm">{errorMsg}</Text>
            </Alert>
          )}
          <Button type="submit" loading={login.isPending} fullWidth size="md" radius="md">
            {m.auth_login_submit()}
          </Button>
        </Stack>
      </form>
    </AuthLayout>
  )
}

export const Route = createFileRoute('/login')({
  component: LoginPage,
})
