<script setup lang="ts">
import { ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'

import { useAuthStore } from '@/stores/auth'

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

const username = ref('')
const password = ref('')

async function handleSubmit() {
  const success = await authStore.login(username.value, password.value)
  if (success) {
    const redirect = route.query.redirect as string
    router.push(redirect || '/campaign')
  }
}
</script>

<template>
  <div class="container mx-auto px-4 py-16">
    <div class="max-w-md mx-auto">
      <h1 class="text-3xl font-bold text-center mb-8">
        Login
      </h1>

      <form
        class="space-y-6"
        @submit.prevent="handleSubmit"
      >
        <div
          v-if="authStore.error"
          class="bg-error/20 text-error p-4 rounded"
        >
          {{ authStore.error }}
        </div>

        <div>
          <label
            for="username"
            class="block text-sm font-medium mb-2"
          >
            Username
          </label>
          <input
            id="username"
            v-model="username"
            type="text"
            required
            class="w-full px-4 py-2 bg-surface rounded border border-gray-600 focus:border-primary focus:outline-none"
          >
        </div>

        <div>
          <label
            for="password"
            class="block text-sm font-medium mb-2"
          >
            Password
          </label>
          <input
            id="password"
            v-model="password"
            type="password"
            required
            class="w-full px-4 py-2 bg-surface rounded border border-gray-600 focus:border-primary focus:outline-none"
          >
        </div>

        <button
          type="submit"
          :disabled="authStore.isLoading"
          class="btn btn-primary w-full py-3"
        >
          {{ authStore.isLoading ? 'Logging in...' : 'Login' }}
        </button>
      </form>

      <p class="mt-6 text-center text-gray-400">
        Don't have an account?
        <RouterLink
          to="/register"
          class="text-primary-light hover:underline"
        >
          Sign up
        </RouterLink>
      </p>
    </div>
  </div>
</template>
