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

const companies = ref<Company[]>([])
const plans = ref<Plan[]>([])
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 billingCycle = ref<'monthly' | 'yearly'>('monthly')
const canManageSubscriptions = computed(() => companyContext.hasPermission('subscriptions.manage'))
const activeCompany = computed(() => companies.value.find((company) => String(company.id) === currentCompanyId.value) || companyContext.company)
const activeCompanies = computed(() => companies.value.filter((company) => company.status === 'active').length)
const managedCompanies = computed(() => companies.value.filter((company) => ['owner', 'admin'].includes(company.user_role || '')).length)
const availablePlans = computed(() => plans.value.filter((plan) => plan.is_active !== false))
const currentPlanId = computed(() => activeCompany.value?.subscription?.plan.id || null)
const form = ref({
  name: '',
  email: '',
  phone: '',
  currency: 'BDT',
  timezone: 'Asia/Dhaka',
})

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

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

function setSuccess(message: string) {
  error.value = ''
  success.value = message
}

function money(value: string | number) {
  return Number(value || 0).toFixed(2)
}

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'
}

async function load() {
  loading.value = true
  clearMessages()

  try {
    const [companyData, planData] = await Promise.all([
      companyService.list(),
      planService.list(),
    ])
    companies.value = companyData
    plans.value = planData

    if (!currentCompanyId.value && companyData.length > 0) {
      selectCompany(companyData[0], true)
    } else if (currentCompanyId.value) {
      await companyContext.loadCurrent(true)
    }
  } catch (loadError) {
    setError(loadError, 'Unable to load company settings.')
  } finally {
    loading.value = false
  }
}

async function createCompany() {
  saving.value = true
  clearMessages()

  try {
    const company = await companyService.create(form.value)
    companies.value = [...companies.value, company]
    selectCompany(company, true)
    form.value = {
      name: '',
      email: '',
      phone: '',
      currency: 'BDT',
      timezone: 'Asia/Dhaka',
    }
    setSuccess(`${company.name} workspace created and selected.`)
  } catch (createError) {
    setError(createError, 'Unable to create company.')
  } finally {
    saving.value = false
  }
}

async function switchPlan(plan: Plan) {
  if (!currentCompanyId.value) {
    error.value = 'Select a company first.'
    success.value = ''
    return
  }

  saving.value = true
  clearMessages()

  try {
    await planService.switchPlan({
      plan_id: plan.id,
      billing_cycle: billingCycle.value,
    })
    const company = await companyContext.loadCurrent(true)
    await load()

    if (company) {
      selectCompany(company, true)
    }
    setSuccess(`${plan.name} plan is now active.`)
  } catch (switchError) {
    setError(switchError, 'Unable to switch plan. Owner or admin access is required.')
  } finally {
    saving.value = false
  }
}

function selectCompany(company: Company, silent = false) {
  currentCompanyId.value = String(company.id)
  companyContext.selectCompany(company)
  void companyContext.loadCurrent(true)
  if (!silent) {
    setSuccess(`${company.name} selected.`)
  }
}

onMounted(load)
</script>

<template>
  <section class="grid">
    <article class="panel">
      <h2>Companies</h2>
      <p v-if="loading">Loading companies...</p>
      <p v-if="error" class="error">{{ error }}</p>
      <p v-if="success" class="success">{{ success }}</p>

      <div class="grid compact-grid">
        <article class="metric">
          <span>Total</span>
          <strong>{{ companies.length }}</strong>
        </article>
        <article class="metric">
          <span>Active</span>
          <strong>{{ activeCompanies }}</strong>
        </article>
        <article class="metric">
          <span>Managed</span>
          <strong>{{ managedCompanies }}</strong>
        </article>
        <article class="metric">
          <span>Current Plan</span>
          <strong>{{ activeCompany?.subscription?.plan.name || 'None' }}</strong>
        </article>
      </div>

      <div v-if="!loading" class="stack">
        <div v-for="company in companies" :key="company.id" class="list-item">
          <div>
            <strong>{{ company.name }}</strong>
            <span>{{ company.slug }} - {{ company.currency }}</span>
            <span>{{ company.subscription?.plan.name || 'No active plan' }}</span>
            <span v-if="company.subscription">
              {{ company.subscription.billing_cycle }} - {{ company.subscription.renews_at ? `renews ${company.subscription.renews_at}` : company.subscription.status }}
            </span>
          </div>
          <div class="inline-actions">
            <span :class="statusClass(company.status)">{{ company.status }}</span>
            <span :class="statusClass(company.subscription?.status || 'none')">{{ company.subscription?.status || 'no subscription' }}</span>
            <span class="status-pill off">{{ company.user_role || 'member' }}</span>
            <button class="button ghost" type="button" :disabled="saving || currentCompanyId === String(company.id)" @click="selectCompany(company)">
              {{ currentCompanyId === String(company.id) ? 'Selected' : 'Use' }}
            </button>
          </div>
        </div>

        <p v-if="companies.length === 0">No company workspace yet.</p>
      </div>
    </article>

    <article class="panel">
      <h2>Create Company</h2>
      <form class="form" @submit.prevent="createCompany">
        <div class="field">
          <label for="company_name">Company Name</label>
          <input id="company_name" v-model="form.name" type="text" required />
        </div>
        <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 class="field">
          <label for="company_currency">Currency</label>
          <input id="company_currency" v-model="form.currency" maxlength="3" type="text" />
        </div>
        <div class="field">
          <label for="company_timezone">Timezone</label>
          <select id="company_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>
        <button class="button primary" type="submit" :disabled="saving">
          {{ saving ? 'Creating...' : 'Create Company' }}
        </button>
      </form>
    </article>

    <article class="panel">
      <h2>Plans</h2>
      <div class="field">
        <label for="billing_cycle">Billing Cycle</label>
        <select id="billing_cycle" v-model="billingCycle">
          <option value="monthly">Monthly</option>
          <option value="yearly">Yearly</option>
        </select>
      </div>
      <div class="stack">
        <div v-for="plan in availablePlans" :key="plan.id" class="list-item">
          <div>
            <strong>{{ plan.name }}</strong>
            <span v-if="plan.description">{{ plan.description }}</span>
            <span>{{ plan.features.map((feature) => feature.name).join(', ') }}</span>
            <span>{{ plan.max_users || 'Unlimited' }} users - {{ plan.max_branches || 'Unlimited' }} branches</span>
          </div>
          <div class="inline-actions">
            <span>BDT {{ money(billingCycle === 'monthly' ? plan.monthly_price : plan.yearly_price) }}</span>
            <button
              v-if="canManageSubscriptions"
              class="button ghost"
              type="button"
              :disabled="saving || !currentCompanyId || currentPlanId === plan.id"
              @click="switchPlan(plan)"
            >
              {{ currentPlanId === plan.id ? 'Active' : 'Use Plan' }}
            </button>
          </div>
        </div>
        <p v-if="availablePlans.length === 0">No active plans available.</p>
      </div>
    </article>
  </section>
</template>
