---
import { actions } from 'astro:actions'

import Button from '../../components/Button.astro'
import InputLoginToken from '../../components/InputLoginToken.astro'
import MiniLayout from '../../layouts/MiniLayout.astro'
import { logout } from '../../lib/userCookies'

const result = Astro.getActionResult(actions.account.login)
if (result && !result.error) {
  return Astro.redirect(result.data.redirect)
}

if (Astro.url.searchParams.get('logout')) {
  await logout(Astro)
  const url = new URL(Astro.url)
  url.searchParams.delete('logout')
  return Astro.redirect(url.toString())
}

// Redirect if already logged in
if (Astro.locals.user) {
  // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
  return Astro.redirect(Astro.url.searchParams.get('redirect') || '/')
}

const message = Astro.url.searchParams.get('message')
---

<MiniLayout
  pageTitle="Login"
  description="Login to your account"
  ogImage={{
    template: 'generic',
    title: 'Login',
    description: message ?? 'Enter your login key',
    icon: 'ri:login-box-line',
  }}
  layoutHeader={{
    icon: 'ri:user-line',
    title: 'Welcome back',
    subtitle: message ?? 'Enter your login key',
  }}
  breadcrumbs={[
    {
      name: 'Accounts',
      url: '/account',
    },
    {
      name: 'Login',
    },
  ]}
>
  <form method="POST" action={actions.account.login} aria-label="Log in">
    {/* eslint-disable-next-line astro/jsx-a11y/no-autofocus */}
    <InputLoginToken name="token" autofocus />

    <Button
      type="submit"
      label="Login"
      icon="ri:login-box-line"
      class="mt-4 w-full"
      color="success"
      shadow
      size="lg"
    />
  </form>

  <div
    class="before:bg-day-500/30 after:bg-day-500/30 xs:my-8 my-6 flex items-center gap-2 before:h-px before:w-full after:h-px after:w-full"
  >
    <span class="text-day-400 leading-none">or</span>
  </div>

  <p class="text-day-500 -mt-2 mb-1 text-center">Don't have an anonymous account?</p>

  <Button
    as="a"
    href="/account/generate"
    dataAstroReload
    label="Create account"
    icon="ri:user-add-line"
    class="w-full"
    color="gray"
    size="lg"
  />
</MiniLayout>
