<script setup lang="ts">
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'

const router = useRouter()
const { toast } = useToast()
const { login, isLoading } = useAuth()

const email = ref('')
const password = ref('')
const error = ref('')

const handleLogin = async () => {
  try {
    error.value = ''

    // Use the BFF login endpoint via useAuth
    const result = await login(email.value, password.value)

    if (result.success) {
      toast.success('Login successful!')
      // Redirect to home
      router.push('/')
    } else {
      error.value = result.error || 'Login failed'
      toast.error(result.error || 'Login failed')
    }
  } catch (e: any) {
    error.value = e.message || 'Login failed'
    toast.error(e.message || 'Login failed')
  }
}
</script>

<template>
  <form @submit.prevent="handleLogin" class="flex flex-col gap-6">
    <div class="flex flex-col items-center gap-2 text-center">
      <h1 class="text-2xl font-bold">Login to your account</h1>
      <p class="text-balance text-sm text-muted-foreground">
        Enter your credentials below to login
      </p>
    </div>

    <div v-if="error" class="p-3 bg-destructive/10 text-destructive rounded text-sm">
      {{ error }}
    </div>

    <div class="grid gap-6">
      <div class="grid gap-2">
        <Label for="email">Email</Label>
        <Input id="email" v-model="email" type="email" placeholder="m@example.com" required />
      </div>
      <div class="grid gap-2">
        <div class="flex items-center">
          <Label for="password">Password</Label>
          <a href="#" class="ml-auto text-sm underline-offset-4 hover:underline">
            Forgot your password?
          </a>
        </div>
        <Input id="password" v-model="password" type="password" required />
      </div>
      <Button type="submit" class="w-full" :disabled="isLoading">
        {{ isLoading ? 'Logging in...' : 'Login' }}
      </Button>
    </div>
    <div class="text-center text-sm">
      Don't have an account?
      <NuxtLink to="/register" class="underline underline-offset-4">Sign up</NuxtLink>
    </div>
  </form>
</template>
