<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 { toast } = useToast()

// Cookie for server-side auth check
const tokenCookie = useCookie('token')

// Extract subdomain from hostname (e.g., tenant1.localhost → tenant1)
const getSubdomain = () => {
  if (!import.meta.client) return null
  const hostname = window.location.hostname
  const parts = hostname.split('.')
  
  console.log('Extracting subdomain from:', hostname, 'parts:', parts)
  
  // For localhost development: tenant1.localhost or localhost
  if (hostname === 'localhost' || hostname === '127.0.0.1') {
    return null // Use default tenant for plain localhost
  }
  
  // For subdomains like tenant1.routebox.co or tenant1.localhost
  if (parts.length >= 2 && parts[0] !== 'www') {
    console.log('Using subdomain:', parts[0])
    return parts[0] // Return subdomain
  }
  
  return null
}

const subdomain = ref(getSubdomain())
const email = ref('')
const password = ref('')
const loading = ref(false)
const error = ref('')

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

    const headers: Record<string, string> = {
      'Content-Type': 'application/json',
    }

    // Only send x-tenant-id if we have a subdomain
    if (subdomain.value) {
      headers['x-tenant-id'] = subdomain.value
    }

    const response = await fetch(`${config.public.apiBaseUrl}/api/auth/login`, {
      method: 'POST',
      headers,
      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 in localStorage
    // Store the tenant ID that was used for login
    const tenantToStore = subdomain.value || data.user?.tenantId || 'tenant1'
    localStorage.setItem('tenantId', tenantToStore)
    localStorage.setItem('token', data.access_token)
    localStorage.setItem('user', JSON.stringify(data.user))
    
    // Also store token in cookie for server-side auth check
    tokenCookie.value = data.access_token

    toast.success('Login successful!')
    
    // Redirect to home
    router.push('/')
  } catch (e: any) {
    error.value = e.message || 'Login failed'
    toast.error(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="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>
