<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { RouterLink, RouterView, useRoute } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { useCompanyContextStore } from '@/stores/companyContext'
import { getApiErrorMessage } from '@/services/api'
import { authService } from '@/modules/auth/services/authService'

const auth = useAuthStore()
const companyContext = useCompanyContextStore()
const route = useRoute()

const moduleLinks = [
  { to: '/invoices', label: 'Invoice', feature: 'invoice', permission: 'invoice.view' },
  { to: '/pos', label: 'POS', feature: 'pos', permission: 'pos.view' },
  { to: '/inventory', label: 'Inventory', feature: 'inventory', permission: 'inventory.view' },
  { to: '/finance', label: 'Finance', feature: 'accounting', permission: 'accounting.view' },
  { to: '/crm', label: 'CRM', feature: 'crm', permission: 'crm.view' },
  { to: '/reports', label: 'Reports', feature: 'reports', permission: 'reports.view' },
  { to: '/notifications', label: 'Notifications', feature: 'notification', permission: 'notification.view' },
]

const visibleModuleLinks = computed(() => {
  return moduleLinks.filter((link) => {
    return companyContext.hasFeature(link.feature) && companyContext.hasPermission(link.permission)
  })
})
const isCustomerPortalRoute = computed(() => route.path.startsWith('/customer-portal'))
const showWorkspaceNav = computed(() => auth.isAuthenticated)
const canManageSettings = computed(() => companyContext.hasPermission('settings.manage'))
const canManageUsers = computed(() => companyContext.hasPermission('users.manage'))
const verificationMessage = ref('')
const verificationError = ref('')
const sendingVerification = ref(false)

async function resendVerificationEmail() {
  sendingVerification.value = true
  verificationMessage.value = ''
  verificationError.value = ''

  try {
    verificationMessage.value = await authService.resendEmailVerification()
  } catch (resendError) {
    verificationError.value = getApiErrorMessage(resendError, 'Unable to send verification email.')
  } finally {
    sendingVerification.value = false
  }
}

onMounted(async () => {
  if (auth.isAuthenticated) {
    await auth.refreshUser().catch(() => undefined)
    void companyContext.loadCurrent()
  }
})
</script>

<template>
  <RouterView v-if="isCustomerPortalRoute" />

  <div v-else class="app-shell">
    <aside class="sidebar">
      <RouterLink class="brand" to="/">BizNovia</RouterLink>
      <div v-if="companyContext.company" class="sidebar-context">
        <strong>{{ companyContext.company.name }}</strong>
        <span>{{ companyContext.planName }}</span>
      </div>
      <nav v-if="showWorkspaceNav">
        <RouterLink to="/">Dashboard</RouterLink>
        <RouterLink v-for="link in visibleModuleLinks" :key="link.to" :to="link.to">{{ link.label }}</RouterLink>
        <RouterLink to="/settings/companies">Companies</RouterLink>
        <RouterLink v-if="canManageUsers" to="/settings/members">Employees</RouterLink>
        <RouterLink v-if="auth.user?.is_super_admin" to="/super-admin">Super Admin</RouterLink>
        <RouterLink v-if="canManageSettings" to="/settings">Settings</RouterLink>
      </nav>
      <nav v-else>
        <RouterLink to="/login">Login</RouterLink>
        <RouterLink to="/register">Register</RouterLink>
      </nav>
    </aside>

    <main class="content">
      <header class="topbar">
        <div>
          <p class="eyebrow">Business Operating System</p>
          <h1>Modular SaaS Workspace</h1>
        </div>
        <div class="topbar-actions">
          <RouterLink v-if="!auth.isAuthenticated" class="button ghost" to="/login">Login</RouterLink>
          <RouterLink v-if="!auth.isAuthenticated" class="button primary" to="/register">Register</RouterLink>
          <button v-else class="button ghost" type="button" @click="auth.logout()">Logout</button>
        </div>
      </header>

      <section v-if="auth.user && !auth.user.email_verified_at" class="notice-bar">
        <div>
          <strong>Email verification required</strong>
          <span>{{ verificationMessage || verificationError || 'Verify your email address to secure this account.' }}</span>
        </div>
        <button class="button ghost" type="button" :disabled="sendingVerification" @click="resendVerificationEmail">
          {{ sendingVerification ? 'Sending...' : 'Resend Email' }}
        </button>
      </section>

      <RouterView />
    </main>
  </div>
</template>
