---
import AdminLoginLayout from '@layouts/admin/AdminLoginLayout.astro';
import Password from '@components/input/Password.svelte';
import Input from '@components/input/Input.svelte';
import Popup from '@components/popup/Popup.svelte';
---

<AdminLoginLayout title="Login">
  <div class="flex justify-center items-center w-full h-screen">
    <div class="card w-96 px-6 py-6 shadow-lg">
      <h1 class="text-3xl text-center">Admin Login</h1>
      <div class="divider"></div>
      <form id="login" class="flex flex-col items-center">
        <div>
          <Input id="username" type="text" label="Nutzername" required />
          <Password id="password" label="Passwort" required client:load />
        </div>
        <div class="mt-4">
          <button class="btn btn-neutral">Login</button>
        </div>
      </form>
    </div>
  </div>
</AdminLoginLayout>

<Popup client:idle />

<script>
  import { actions } from 'astro:actions';
  import { popupState } from '@components/popup/Popup';

  const loginForm = document.getElementById('login') as HTMLFormElement;
  loginForm.addEventListener('submit', async (e) => {
    e.preventDefault();

    const usernameInput = document.getElementById('username') as HTMLInputElement;
    const passwordInput = document.getElementById('password') as HTMLInputElement;

    const { error } = await actions.session.login({
      username: usernameInput.value,
      password: passwordInput.value
    });
    if (error) {
      popupState.set({ type: 'error', title: 'Fehler', message: error.message });
      return;
    }
    window.location.href = 'admin';
  });
</script>
