<script setup>
import { ref } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import InputText from 'primevue/inputtext';
import Password from 'primevue/password';
import Button from 'primevue/button';
import Message from 'primevue/message';
import { login } from '../store/auth.js';

const router = useRouter();
const route = useRoute();

const username = ref('admin');
const password = ref('');
const error = ref('');
const loading = ref(false);

async function handleSubmit() {
  error.value = '';
  loading.value = true;
  try {
    await login(username.value, password.value);
    router.push(route.query.redirect || { name: 'dashboard' });
  } catch (e) {
    error.value = e.response?.data?.error || 'Unable to log in. Please try again.';
  } finally {
    loading.value = false;
  }
}
</script>

<template>
  <div class="login-screen">
    <div class="login-card">
      <div class="brand-mark">M</div>
      <h1>Medicus</h1>
      <p class="subtitle">Sign in to continue — POC build</p>

      <form @submit.prevent="handleSubmit">
        <div class="field">
          <label for="username">Username</label>
          <InputText id="username" v-model="username" autofocus fluid />
        </div>
        <div class="field">
          <label for="password">Password</label>
          <Password id="password" v-model="password" :feedback="false" toggleMask fluid />
        </div>

        <Message v-if="error" severity="error" :closable="false">{{ error }}</Message>

        <Button type="submit" label="Sign in" :loading="loading" fluid class="submit-btn" />
      </form>

      <p class="hint">Demo credentials: <span class="mono">admin</span> / <span class="mono">Medicus2026</span></p>
    </div>
  </div>
</template>

<style scoped>
.login-screen {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--color-text);
}

.login-card {
  background: var(--color-surface);
  border-radius: 14px;
  padding: 2.5rem;
  width: 360px;
  text-align: center;
}

.brand-mark {
  width: 48px;
  height: 48px;
  margin: 0 auto 1rem;
  border-radius: 10px;
  background: var(--color-accent);
  display: flex;
  align-items: center;
  justify-content: center;
  font-family: var(--font-display);
  font-weight: 700;
  font-size: 1.4rem;
}

h1 {
  font-size: 1.5rem;
}

.subtitle {
  color: var(--color-text-muted);
  font-size: 0.85rem;
  margin-bottom: 1.5rem;
}

.field {
  text-align: left;
  margin-bottom: 1rem;
}

.field label {
  display: block;
  font-size: 0.8rem;
  font-weight: 500;
  margin-bottom: 0.35rem;
}

.submit-btn {
  margin-top: 0.5rem;
}

.hint {
  margin-top: 1.5rem;
  font-size: 0.75rem;
  color: var(--color-text-muted);
}
</style>
