<template>
  <div class="min-h-screen w-full flex items-center justify-center">
    <div class="flex items-center justify-center py-12 w-full">
      <div class="mx-auto grid w-[350px] gap-6">
        <div class="grid gap-2 text-center">
          <h1 class="text-3xl font-bold">Login</h1>
          <p class="text-balance text-muted-foreground">
            Enter your email below to login to your account
          </p>
        </div>
        
        <form @submit.prevent="handleSubmit" class="grid gap-4">
          <div class="grid gap-2">
            <Label for="email">Email</Label>
            <Input
              id="email"
              v-model="form.email"
              type="email"
              placeholder="m@example.com"
              required
              :disabled="isLoading"
            />
          </div>
          
          <div class="grid gap-2">
            <div class="flex items-center">
              <Label for="password">Password</Label>
              <a href="#" class="ml-auto inline-block text-sm underline">
                Forgot your password?
              </a>
            </div>
            <Input
              id="password"
              v-model="form.password"
              type="password"
              required
              :disabled="isLoading"
            />
          </div>
          
          <Button type="submit" class="w-full" :disabled="isLoading">
            <Loader2 v-if="isLoading" class="mr-2 h-4 w-4 animate-spin" />
            Login
          </Button>
          
          <div v-if="error" class="text-sm text-destructive text-center">
            {{ error }}
          </div>
        </form>
        
        <div class="mt-4 text-center text-sm">
          Don&apos;t have an account?{" "}
          <router-link to="/register" class="underline">
            Sign up
          </router-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Loader2 } from 'lucide-vue-next'
import { useAuthStore } from '@/stores/auth'
import type { LoginCredentials } from '@/types/auth'

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

const form = reactive<LoginCredentials>({
  email: '',
  password: ''
})

const isLoading = computed(() => authStore.isLoading)
const error = computed(() => authStore.error)

const handleSubmit = async () => {
  try {
    authStore.clearError()
    await authStore.login(form)
    
    // Redirect to dashboard after successful login
    router.push('/')
  } catch (err) {
    // Error is handled by the store
    console.error('Login error:', err)
  }
}

</script>