import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { startTransition, useState } from 'react'
import { m } from '@/i18n/messages'
import { useLocale } from '@/i18n/config'
import { useQueryClient } from '@tanstack/react-query'
import {
  Alert,
  Button,
  Container,
  Paper,
  PasswordInput,
  Stack,
  Text,
  TextInput,
  Title,
} from '@pikku/mantine/core'
import { BrandMark } from '../components/Brand'
import { signIn } from '../lib/auth'

function LoginPage() {
  useLocale()
  const navigate = useNavigate()
  const qc = useQueryClient()
  const [email, setEmail] = useState(import.meta.env.DEV ? 'sarah@seminarhof.example' : '')
  const [password, setPassword] = useState(import.meta.env.DEV ? 'owner1234' : '')
  const [isPending, setIsPending] = useState(false)
  const [error, setError] = useState(false)

  const handleSubmit = async () => {
    setIsPending(true)
    setError(false)
    try {
      await signIn(email, password)
      await qc.invalidateQueries({ queryKey: ['me'] })
      startTransition(() => {
        navigate({ to: '/' })
      })
    } catch {
      setError(true)
    } finally {
      setIsPending(false)
    }
  }

  return (
    <Container
      size="xs"
      style={{
        minHeight: '100vh',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      }}
    >
      <Paper withBorder radius="md" p="lg" w="100%">
        <Stack gap="md" align="stretch">
          <Stack gap={4} align="center">
            <BrandMark size={64} />
            <Title order={2} ta="center" c="var(--brand-plum)">{m.auth__login__title()}</Title>
            <Text size="sm" c="dimmed" ta="center">{m.auth__login__subtitle()}</Text>
          </Stack>
          <TextInput
            type="email"
            label={m.auth__login__email()}
            placeholder={m.auth__login__email_placeholder()}
            value={email}
            onChange={(e) => setEmail(e.currentTarget.value)}
          />
          <PasswordInput
            label={m.auth__login__password()}
            value={password}
            onChange={(e) => setPassword(e.currentTarget.value)}
          />
          {error && (
            <Alert color="red">{m.auth__login__errors__invalid_credentials()}</Alert>
          )}
          <Button
            onClick={handleSubmit}
            disabled={!email || !password || isPending}
            loading={isPending}
          >
            {m.auth__login__submit()}
          </Button>
        </Stack>
      </Paper>
    </Container>
  )
}

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