<template>
  <div class="mx-auto max-w-sm space-y-6">
    <div class="space-y-2 text-center">
      <h1 class="text-3xl font-bold">Sign In</h1>
      <p class="text-muted-foreground">
        Enter your credentials to access your account
      </p>
    </div>
    
    <form @submit.prevent="handleSubmit" class="space-y-4">
      <div class="space-y-2">
        <Label for="email">Email</Label>
        <Input
          id="email"
          v-model="form.email"
          type="email"
          placeholder="Enter your email"
          required
          :disabled="isLoading"
        />
      </div>
      
      <div class="space-y-2">
        <Label for="password">Password</Label>
        <Input
          id="password"
          v-model="form.password"
          type="password"
          placeholder="Enter your 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" />
        Sign In
      </Button>
      
      <div v-if="error" class="text-sm text-destructive text-center">
        {{ error }}
      </div>
    </form>
    
    <div class="text-center text-sm">
      Don't have an account?
      <router-link to="/register" class="underline underline-offset-4 hover:text-primary">
        Sign up
      </router-link>
    </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>