<script setup>
import { toast } from 'bulma-toast'

const loading = ref(true)
const saving = ref(false)
const notFound = ref(false)
const companyName = ref('')
const eMailInvoice = ref('')
const savedEmail = ref('')

const retrieve = async () => {
  loading.value = true
  try {
    const res = await $fetch('/api/accounts/company-profile', {
      headers: useRequestHeaders(['cookie'])
    })
    if (Number(res?.status) === 200) {
      companyName.value = res.companyName || ''
      eMailInvoice.value = res.eMailInvoice || ''
      savedEmail.value = eMailInvoice.value
    } else {
      notFound.value = true
    }
  } catch (err) {
    console.error('Error loading company profile:', err)
    notFound.value = true
  }
  loading.value = false
}
onMounted(retrieve)

const isDirty = computed(() => eMailInvoice.value.trim() !== savedEmail.value)
const isValidEmail = computed(() => {
  const val = eMailInvoice.value.trim()
  return val === '' || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(val)
})

const save = async () => {
  if (!isValidEmail.value) {
    toast({
      message: 'Please enter a valid email address',
      type: 'is-warning',
      duration: 2000
    })
    return
  }
  saving.value = true
  try {
    const res = await $fetch('/api/accounts/company-profile', {
      method: 'PUT',
      headers: useRequestHeaders(['cookie']),
      body: { eMailInvoice: eMailInvoice.value.trim() }
    })
    if (Number(res?.status) === 200) {
      eMailInvoice.value = res.eMailInvoice || ''
      savedEmail.value = eMailInvoice.value
      toast({
        message: 'Saved!',
        type: 'is-success',
        duration: 2000
      })
    } else {
      toast({
        message: res?.message || 'Save error',
        type: 'is-danger',
        duration: 3000
      })
    }
  } catch (err) {
    console.error('Error saving company profile:', err)
    toast({
      message: 'Save error',
      type: 'is-danger',
      duration: 3000
    })
  }
  saving.value = false
}
</script>

<template>
  <section class="billingCard">
    <header class="billingCard__header">
      <h3 class="billingCard__title">Billing</h3>
      <p class="billingCard__sub">Settings for the invoices we issue to your company.</p>
    </header>

    <div v-if="loading" class="billingCard__state">Loading…</div>
    <div v-else-if="notFound" class="billingCard__state">
      No company record is linked to your account yet — please contact support.
    </div>
    <template v-else>
      <div class="billingField">
        <label class="label">Company</label>
        <input type="text" :value="companyName" class="input" readonly />
      </div>

      <div class="billingField">
        <label class="label">Invoice Email</label>
        <input
          type="email"
          v-model="eMailInvoice"
          class="input"
          :class="{ 'is-danger': !isValidEmail }"
          placeholder="e.g. accounting@your-company.com"
        />
        <p class="billingField__hint">
          Invoices are sent to this address. Leave empty to use your general contact email instead.
        </p>
      </div>

      <div class="billingCard__actions">
        <button
          type="button"
          class="button is-primary"
          @click="save"
          :disabled="saving || !isDirty || !isValidEmail"
        >
          <span v-if="saving">Saving…</span>
          <span v-else>Save</span>
        </button>
      </div>
    </template>
  </section>
</template>

<style scoped>
.billingCard {
  max-width: 720px;
  background: var(--theme-bg-primary, #fff);
  border: 1px solid var(--theme-border, #e2e2e2);
  border-radius: 12px;
  padding: 2rem;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
}
.billingCard__header {
  margin-bottom: 1.5rem;
  padding-bottom: 1rem;
  border-bottom: 1px solid var(--theme-border, #efefef);
}
.billingCard__title {
  font-size: 1.25rem;
  font-weight: 600;
  margin: 0 0 0.25rem 0;
  color: var(--theme-text-primary, #2b2b2b);
}
.billingCard__sub {
  font-size: 0.85rem;
  color: var(--theme-text-secondary, #777);
  margin: 0;
}
.billingCard__state {
  font-size: 0.9rem;
  color: var(--theme-text-secondary, #777);
  padding: 0.5rem 0;
}
.billingField {
  margin-bottom: 1.25rem;
}
.billingField__hint {
  font-size: 0.78rem;
  color: var(--theme-text-secondary, #888);
  margin-top: 0.35rem;
}
.billingCard__actions {
  display: flex;
  justify-content: flex-end;
  padding-top: 0.5rem;
  border-top: 1px solid var(--theme-border, #efefef);
}
@media (max-width: 640px) {
  .billingCard {
    padding: 1.25rem;
  }
}
</style>
