<script setup lang="ts">
import { ref } from 'vue'
import { RouterLink, useRouter } from 'vue-router'
import { getApiErrorMessage } from '@/services/api'
import { customerPortalService } from '@/modules/customerPortal/services/customerPortalService'

const router = useRouter()
const loading = ref(false)
const error = ref('')
const form = ref({
  company_slug: '',
  email: '',
  password: '',
})

async function login() {
  loading.value = true
  error.value = ''

  try {
    const data = await customerPortalService.login({
      company_slug: form.value.company_slug.trim(),
      email: form.value.email.trim(),
      password: form.value.password,
      device_name: 'web-customer-portal',
    })

    localStorage.setItem('customer_portal_token', data.token)
    localStorage.setItem('customer_portal_account', JSON.stringify(data.account))
    await router.push('/customer-portal')
  } catch (loginError) {
    error.value = getApiErrorMessage(loginError, 'Company, email, or password did not match.')
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <main class="portal-layout">
    <section class="portal-card form-page">
      <div>
        <p class="eyebrow">Customer Portal</p>
        <h1>BizNovia</h1>
      </div>
      <form class="form" @submit.prevent="login">
        <p v-if="error" class="error">{{ error }}</p>
        <div class="field">
          <label for="company_slug">Company Slug</label>
          <input id="company_slug" v-model="form.company_slug" autocomplete="organization" type="text" required />
        </div>
        <div class="field">
          <label for="portal_email">Email</label>
          <input id="portal_email" v-model="form.email" autocomplete="email" type="email" required />
        </div>
        <div class="field">
          <label for="portal_password">Password</label>
          <input id="portal_password" v-model="form.password" autocomplete="current-password" type="password" required />
        </div>
        <button class="button primary" type="submit" :disabled="loading">
          {{ loading ? 'Signing in...' : 'Login' }}
        </button>
      </form>
      <RouterLink class="button ghost" to="/login">Company login</RouterLink>
    </section>
  </main>
</template>
