<script setup>
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { defaultRouteForRole, isDashboardRole } from '@/composables/roleAccess'
import Button from '@/components/ui/Button.vue'

const router = useRouter()
const route = useRoute()
const auth = useAuthStore()

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

async function submit() {
  error.value = ''
  loading.value = true
  try {
    await auth.login(username.value, password.value)
    if (!isDashboardRole(auth.role)) {
      auth.logout()
      error.value = 'This account is for API integration only. Sign in with a clinical user.'
      return
    }
    const redirect = typeof route.query.redirect === 'string' ? route.query.redirect : defaultRouteForRole(auth.role)
    await router.push(redirect)
  } catch (e) {
    error.value = e.message ?? 'Login failed'
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <div class="flex min-h-screen items-center justify-center bg-gray-50 px-4 dark:bg-gray-950">
    <form
      class="w-full max-w-sm space-y-4 rounded-lg border border-gray-200 bg-white p-6 shadow-sm dark:border-gray-800 dark:bg-gray-900"
      @submit.prevent="submit"
    >
      <div>
        <h1 class="text-xl font-bold text-gray-900 dark:text-white">VigilCare</h1>
        <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">Sign in to continue</p>
      </div>

      <label class="block">
        <span class="mb-1 block text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400">
          Username
        </span>
        <input
          v-model="username"
          type="text"
          autocomplete="username"
          required
          class="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500/20 dark:border-gray-700 dark:bg-gray-950 dark:text-white"
        />
      </label>

      <label class="block">
        <span class="mb-1 block text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400">
          Password
        </span>
        <input
          v-model="password"
          type="password"
          autocomplete="current-password"
          required
          class="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500/20 dark:border-gray-700 dark:bg-gray-950 dark:text-white"
        />
      </label>

      <p v-if="error" class="text-sm text-red-600 dark:text-red-400" role="alert">
        {{ error }}
      </p>

      <Button type="submit" variant="primary" class="w-full" :disabled="loading">
        {{ loading ? 'Signing in…' : 'Sign in' }}
      </Button>
    </form>
  </div>
</template>
