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

const config = useRuntimeConfig()
const router = useRouter()

const tenantId = ref('123')
const email = ref('')
const password = ref('')
const loading = ref(false)
const error = ref('')

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

    const response = await fetch(`${config.public.apiBaseUrl}/api/auth/login`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'x-tenant-id': tenantId.value,
      },
      body: JSON.stringify({
        email: email.value,
        password: password.value,
      }),
    })

    if (!response.ok) {
      const data = await response.json()
      throw new Error(data.message || 'Login failed')
    }

    const data = await response.json()

    // Store credentials
    localStorage.setItem('tenantId', tenantId.value)
    localStorage.setItem('token', data.access_token)
    localStorage.setItem('user', JSON.stringify(data.user))

    // Redirect to home
    router.push('/')
  } catch (e: any) {
    error.value = e.message || 'Login failed'
  } finally {
    loading.value = false
  }
}
</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="tenantId">Tenant ID</Label>
        <Input id="tenantId" v-model="tenantId" type="text" placeholder="123" required />
      </div>
      <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="loading">
        {{ loading ? '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>
