<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { companyService, type Company } from '@/modules/settings/services/companyService'
import { getApiErrorMessage } from '@/services/api'
import { useCompanyContextStore } from '@/stores/companyContext'

const company = ref<Company | null>(null)
const companyContext = useCompanyContextStore()
const loading = ref(false)
const saving = ref(false)
const error = ref('')
const success = ref('')
const currentCompanyId = ref(localStorage.getItem('current_company_id') || '')
const canManageSettings = computed(() => company.value?.permissions?.includes('settings.manage') || false)
const activePlanName = computed(() => company.value?.subscription?.plan.name || 'No active plan')
const subscriptionStatus = computed(() => company.value?.subscription?.status || 'none')
const enabledAlerts = computed(() => [
  form.value.settings.low_stock_alerts,
  form.value.settings.invoice_due_alerts,
  form.value.settings.crm_follow_up_alerts,
].filter(Boolean).length)

const form = ref({
  name: '',
  email: '',
  phone: '',
  address: '',
  currency: 'BDT',
  timezone: 'Asia/Dhaka',
  settings: {
    default_tax_rate: 0,
    invoice_prefix: 'INV',
    pos_prefix: 'POS',
    purchase_prefix: 'PUR',
    expense_prefix: 'EXP',
    payment_terms_days: 0,
    low_stock_alerts: true,
    invoice_due_alerts: true,
    crm_follow_up_alerts: true,
  },
})

function fillForm(data: Company) {
  form.value = {
    name: data.name,
    email: data.email || '',
    phone: data.phone || '',
    address: data.address || '',
    currency: data.currency || 'BDT',
    timezone: data.timezone || 'Asia/Dhaka',
    settings: {
      default_tax_rate: Number(data.settings?.default_tax_rate || 0),
      invoice_prefix: data.settings?.invoice_prefix || 'INV',
      pos_prefix: data.settings?.pos_prefix || 'POS',
      purchase_prefix: data.settings?.purchase_prefix || 'PUR',
      expense_prefix: data.settings?.expense_prefix || 'EXP',
      payment_terms_days: Number(data.settings?.payment_terms_days || 0),
      low_stock_alerts: data.settings?.low_stock_alerts ?? true,
      invoice_due_alerts: data.settings?.invoice_due_alerts ?? true,
      crm_follow_up_alerts: data.settings?.crm_follow_up_alerts ?? true,
    },
  }
}

function clearMessages() {
  error.value = ''
  success.value = ''
}

function setError(settingsError: unknown, fallback: string) {
  success.value = ''
  error.value = getApiErrorMessage(settingsError, fallback)
}

function statusClass(status: string) {
  if (status === 'active' || status === 'trialing') {
    return 'status-pill'
  }

  if (status === 'past_due' || status === 'cancelled' || status === 'inactive') {
    return 'status-pill danger'
  }

  return 'status-pill off'
}

function normalizePrefix(value: string, fallback: string) {
  return (value || fallback).trim().toUpperCase()
}

function validateForm() {
  if (!form.value.name.trim()) {
    error.value = 'Company name is required.'
    success.value = ''
    return false
  }

  if (!form.value.currency.trim() || form.value.currency.trim().length !== 3) {
    error.value = 'Currency must be a 3-letter code.'
    success.value = ''
    return false
  }

  return true
}

async function load() {
  if (!currentCompanyId.value) {
    error.value = 'Select a company workspace first.'
    return
  }

  loading.value = true
  clearMessages()

  try {
    company.value = await companyService.current()
    fillForm(company.value)
  } catch (loadError) {
    setError(loadError, 'Unable to load settings.')
  } finally {
    loading.value = false
  }
}

async function save() {
  if (!canManageSettings.value) {
    error.value = 'Owner or admin access is required.'
    success.value = ''
    return
  }

  if (!validateForm()) {
    return
  }

  saving.value = true
  clearMessages()

  try {
    company.value = await companyService.updateSettings({
      name: form.value.name.trim(),
      email: form.value.email || undefined,
      phone: form.value.phone || undefined,
      address: form.value.address || undefined,
      currency: form.value.currency.trim().toUpperCase(),
      timezone: form.value.timezone,
      settings: {
        default_tax_rate: Number(form.value.settings.default_tax_rate || 0),
        invoice_prefix: normalizePrefix(form.value.settings.invoice_prefix, 'INV'),
        pos_prefix: normalizePrefix(form.value.settings.pos_prefix, 'POS'),
        purchase_prefix: normalizePrefix(form.value.settings.purchase_prefix, 'PUR'),
        expense_prefix: normalizePrefix(form.value.settings.expense_prefix, 'EXP'),
        payment_terms_days: Number(form.value.settings.payment_terms_days || 0),
        low_stock_alerts: form.value.settings.low_stock_alerts,
        invoice_due_alerts: form.value.settings.invoice_due_alerts,
        crm_follow_up_alerts: form.value.settings.crm_follow_up_alerts,
      },
    })
    fillForm(company.value)
    companyContext.selectCompany(company.value)
    await companyContext.loadCurrent(true)
    success.value = 'Settings saved.'
  } catch (saveError) {
    setError(saveError, 'Unable to save settings. Owner or admin access is required.')
  } finally {
    saving.value = false
  }
}

onMounted(load)
</script>

<template>
  <section class="stack">
    <article class="panel">
      <h2>Settings</h2>
      <p v-if="loading">Loading settings...</p>
      <p v-if="error" class="error">{{ error }}</p>
      <p v-if="success" class="success">{{ success }}</p>
      <div v-if="company" class="grid compact-grid">
        <article class="metric">
          <span>Workspace</span>
          <strong>{{ company.name }}</strong>
        </article>
        <article class="metric">
          <span>Plan</span>
          <strong>{{ activePlanName }}</strong>
        </article>
        <article class="metric">
          <span>Status</span>
          <strong :class="statusClass(subscriptionStatus)">{{ subscriptionStatus }}</strong>
        </article>
        <article class="metric">
          <span>Alerts</span>
          <strong>{{ enabledAlerts }}/3</strong>
        </article>
      </div>
    </article>

    <form class="stack" @submit.prevent="save">
      <p v-if="company && !canManageSettings" class="muted">Owner or admin access is required to edit company settings.</p>
      <section class="grid wide-grid">
        <article class="panel">
          <h2>Company Profile</h2>
          <fieldset class="form" :disabled="!canManageSettings">
            <div class="field">
              <label for="company_name">Name</label>
              <input id="company_name" v-model="form.name" type="text" required />
            </div>
            <div class="grid compact-grid">
              <div class="field">
                <label for="company_email">Email</label>
                <input id="company_email" v-model="form.email" type="email" />
              </div>
              <div class="field">
                <label for="company_phone">Phone</label>
                <input id="company_phone" v-model="form.phone" type="text" />
              </div>
            </div>
            <div class="field">
              <label for="company_address">Address</label>
              <textarea id="company_address" v-model="form.address" rows="3"></textarea>
            </div>
            <div class="grid compact-grid">
              <div class="field">
                <label for="currency">Currency</label>
                <input id="currency" v-model="form.currency" maxlength="3" minlength="3" type="text" required />
              </div>
              <div class="field">
                <label for="timezone">Timezone</label>
                <select id="timezone" v-model="form.timezone">
                  <option value="Asia/Dhaka">Asia/Dhaka</option>
                  <option value="UTC">UTC</option>
                  <option value="Asia/Kolkata">Asia/Kolkata</option>
                  <option value="Asia/Dubai">Asia/Dubai</option>
                </select>
              </div>
            </div>
          </fieldset>
        </article>

        <article class="panel">
          <h2>Business Defaults</h2>
          <fieldset class="form" :disabled="!canManageSettings">
            <div class="grid compact-grid">
              <div class="field">
                <label for="tax_rate">Tax Rate</label>
                <input id="tax_rate" v-model.number="form.settings.default_tax_rate" min="0" max="100" step="0.01" type="number" />
              </div>
              <div class="field">
                <label for="payment_terms">Payment Days</label>
                <input id="payment_terms" v-model.number="form.settings.payment_terms_days" min="0" max="365" type="number" />
              </div>
            </div>
            <div class="grid compact-grid">
              <div class="field">
                <label for="invoice_prefix">Invoice Prefix</label>
                <input id="invoice_prefix" v-model="form.settings.invoice_prefix" maxlength="20" type="text" required />
              </div>
              <div class="field">
                <label for="pos_prefix">POS Prefix</label>
                <input id="pos_prefix" v-model="form.settings.pos_prefix" maxlength="20" type="text" required />
              </div>
              <div class="field">
                <label for="purchase_prefix">Purchase Prefix</label>
                <input id="purchase_prefix" v-model="form.settings.purchase_prefix" maxlength="20" type="text" required />
              </div>
              <div class="field">
                <label for="expense_prefix">Expense Prefix</label>
                <input id="expense_prefix" v-model="form.settings.expense_prefix" maxlength="20" type="text" required />
              </div>
            </div>
          </fieldset>
        </article>

        <article class="panel">
          <h2>Alert Rules</h2>
          <fieldset class="form" :disabled="!canManageSettings">
            <label class="inline-actions">
              <input v-model="form.settings.low_stock_alerts" type="checkbox" />
              <span>Low stock alerts</span>
            </label>
            <label class="inline-actions">
              <input v-model="form.settings.invoice_due_alerts" type="checkbox" />
              <span>Invoice due alerts</span>
            </label>
            <label class="inline-actions">
              <input v-model="form.settings.crm_follow_up_alerts" type="checkbox" />
              <span>CRM follow-up alerts</span>
            </label>
          </fieldset>
        </article>
      </section>

      <div class="inline-actions">
        <button v-if="canManageSettings" class="button primary" type="submit" :disabled="saving || loading || !currentCompanyId">
          {{ saving ? 'Saving...' : 'Save Settings' }}
        </button>
        <RouterLink class="button ghost" to="/settings/companies">Companies</RouterLink>
        <RouterLink v-if="company?.permissions?.includes('users.manage')" class="button ghost" to="/settings/members">Employees</RouterLink>
      </div>
    </form>
  </section>
</template>
