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

const route = useRoute()
const router = useRouter()
const companyContext = useCompanyContextStore()
const plans = ref<Plan[]>([])
const billingCycle = ref<'monthly' | 'yearly'>('monthly')
const loading = ref(false)
const saving = ref(false)
const error = ref('')
const success = ref('')

const feature = computed(() => String(route.query.feature || 'module'))

const moduleName = computed(() => {
  return feature.value.charAt(0).toUpperCase() + feature.value.slice(1)
})

const canManagePlan = computed(() => {
  return ['owner', 'admin'].includes(companyContext.company?.user_role || '')
})

const matchingPlans = computed(() => {
  return plans.value.filter((plan) => {
    return plan.is_active !== false && plan.features.some((planFeature) => planFeature.slug === feature.value)
  })
})
const currentPlanId = computed(() => companyContext.company?.subscription?.plan.id || null)

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

function statusClass(plan: Plan) {
  return currentPlanId.value === plan.id ? 'status-pill' : 'status-pill off'
}

function safeRedirectPath() {
  const from = String(route.query.from || '/')

  return from.startsWith('/') && !from.startsWith('//') ? from : '/'
}

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

  try {
    await companyContext.loadCurrent(true)
    plans.value = await planService.list()
  } catch (loadError) {
    error.value = getApiErrorMessage(loadError, 'Unable to load upgrade options.')
  } finally {
    loading.value = false
  }
}

async function switchPlan(plan: Plan) {
  saving.value = true
  error.value = ''
  success.value = ''

  try {
    await planService.switchPlan({
      plan_id: plan.id,
      billing_cycle: billingCycle.value,
    })
    await companyContext.loadCurrent(true)
    success.value = `${plan.name} plan activated.`
    await router.push(safeRedirectPath())
  } catch (switchError) {
    error.value = getApiErrorMessage(switchError, 'Unable to switch plan. Owner or admin access is required.')
  } finally {
    saving.value = false
  }
}

onMounted(load)
</script>

<template>
  <section class="stack">
    <article class="panel stack">
      <h2>Module Locked</h2>
      <p>{{ moduleName }} is not enabled on {{ companyContext.planName }}.</p>
      <p v-if="loading">Loading upgrade options...</p>
      <p v-if="error" class="error">{{ error }}</p>
      <p v-if="success" class="success">{{ success }}</p>
      <div class="inline-actions">
        <RouterLink class="button ghost" to="/settings/companies">View All Plans</RouterLink>
        <RouterLink class="button ghost" to="/">Dashboard</RouterLink>
      </div>
    </article>

    <article class="panel stack">
      <div class="topbar" style="margin-bottom: 0">
        <div>
          <h2>Upgrade Options</h2>
          <p v-if="!canManagePlan">Only company owner or admin can change the plan.</p>
          <p v-else>Choose a plan that includes {{ moduleName }}.</p>
        </div>
        <div class="field">
          <label for="locked_billing_cycle">Billing Cycle</label>
          <select id="locked_billing_cycle" v-model="billingCycle">
            <option value="monthly">Monthly</option>
            <option value="yearly">Yearly</option>
          </select>
        </div>
      </div>

      <div class="grid wide-grid">
        <div v-for="plan in matchingPlans" :key="plan.id" class="panel stack">
          <div>
            <h2>{{ plan.name }}</h2>
            <p>{{ plan.description || 'Plan details' }}</p>
            <span :class="statusClass(plan)">{{ currentPlanId === plan.id ? 'Current Plan' : 'Available' }}</span>
          </div>
          <div class="metric">
            <span>{{ billingCycle }}</span>
            <strong>BDT {{ money(billingCycle === 'monthly' ? plan.monthly_price : plan.yearly_price) }}</strong>
          </div>
          <div>
            <strong>Includes</strong>
            <p>{{ plan.features.map((planFeature) => planFeature.name).join(', ') }}</p>
          </div>
          <button
            class="button primary"
            type="button"
            :disabled="saving || !canManagePlan || currentPlanId === plan.id"
            @click="switchPlan(plan)"
          >
            {{ currentPlanId === plan.id ? 'Current Plan' : 'Upgrade' }}
          </button>
        </div>
      </div>

      <p v-if="matchingPlans.length === 0 && !loading">No active plan currently includes this module.</p>
    </article>
  </section>
</template>
