<template>
  <div>
    <!-- Page Header -->
    <div class="mb-8">
      <h1 class="text-2xl font-bold text-white">{{ $t('permissions.title') }}</h1>
      <p class="text-slate-400 mt-1">{{ $t('permissions.subtitle') }}</p>
    </div>

    <!-- Loading State -->
    <div v-if="loading" class="flex items-center justify-center py-20">
      <svg class="animate-spin h-8 w-8 text-indigo-400" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" />
        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
      </svg>
      <span class="ml-3 text-slate-400">{{ $t('permissions.loading') }}</span>
    </div>

    <!-- Error State -->
    <div v-else-if="error" class="bg-red-500/10 border border-red-500/20 rounded-xl p-6 mb-8">
      <div class="flex items-center gap-3">
        <svg class="w-6 h-6 text-red-400 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
        </svg>
        <div>
          <h3 class="text-red-300 font-medium">{{ $t('permissions.error_title') }}</h3>
          <p class="text-red-400/80 text-sm mt-1">{{ error }}</p>
        </div>
      </div>
      <button @click="fetchAll" class="mt-4 px-4 py-2 text-sm bg-red-600 hover:bg-red-500 text-white rounded-lg transition">
        {{ $t('permissions.retry') }}
      </button>
    </div>

    <!-- Main Content -->
    <template v-else>
      <!-- Save Notification -->
      <div v-if="saveNotification" class="mb-6 px-4 py-3 rounded-lg text-sm font-medium"
        :class="saveNotification.type === 'success'
          ? 'bg-emerald-500/10 border border-emerald-500/20 text-emerald-300'
          : 'bg-red-500/10 border border-red-500/20 text-red-300'">
        {{ saveNotification.message }}
      </div>

      <!-- Save Button (top) -->
      <div v-if="hasModifications" class="mb-6 flex items-center gap-3">
        <button @click="savePermissions"
          class="px-6 py-2.5 bg-emerald-600 hover:bg-emerald-500 text-white font-semibold rounded-lg shadow-lg shadow-emerald-600/20 transition-all hover:scale-[1.02] active:scale-[0.98] flex items-center gap-2">
          <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4" />
          </svg>
          {{ $t('permissions.save_changes') }}
        </button>
        <span class="text-sm text-slate-400">
          {{ $t('permissions.modified_count', { count: modifiedPermissions.size }) }}
        </span>
      </div>

      <!-- Subscription Tier Banner -->
      <div class="bg-indigo-500/10 border border-indigo-500/20 rounded-xl p-4 mb-8 flex items-start gap-3">
        <svg class="w-5 h-5 text-indigo-400 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
        </svg>
        <div class="text-sm text-indigo-300">
          <span class="font-semibold">{{ $t('permissions.current_tier') }}:</span>
          <span class="ml-2 px-2 py-0.5 rounded-full text-xs font-medium"
            :class="tierBadgeClass">
            {{ featureFlags.tier || 'free' }}
          </span>
          <span v-if="featureFlags.expires_at" class="ml-3 text-indigo-400/70">
            {{ $t('permissions.expires') }}: {{ formatDate(featureFlags.expires_at) }}
          </span>
        </div>
      </div>

      <!-- Permission Groups Grid -->
      <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
        <!-- Superadmin Permissions -->
        <div class="bg-slate-800 rounded-xl border border-slate-700 p-6">
          <div class="flex items-center gap-3 mb-4">
            <div class="p-2 rounded-lg bg-purple-500/10 text-purple-400">
              <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12.75L11.25 15 15 9.75m-3-7.036A11.959 11.959 0 013.598 6 11.99 11.99 0 003 9.749c0 5.592 3.824 10.29 9 11.623 5.176-1.332 9-6.03 9-11.622 0-1.31-.21-2.571-.598-3.751h-.152c-3.196 0-6.1-1.248-8.25-3.285z" />
              </svg>
            </div>
            <h2 class="text-lg font-semibold text-white">{{ $t('permissions.superadmin') }}</h2>
          </div>
          <p class="text-sm text-slate-400 mb-4">{{ $t('permissions.superadmin_desc') }}</p>
          <div class="space-y-3">
            <div v-for="perm in superadminPerms" :key="perm.key" class="flex items-center justify-between py-2 border-b border-slate-700/50 last:border-0">
              <span class="text-sm text-slate-300">{{ $t(`permissions.perms.${perm.key}`) }}</span>
              <label class="relative inline-flex items-center cursor-pointer">
                <input type="checkbox" :checked="isPermEnabled('superadmin', perm.key)" class="sr-only peer"
                  @change="handleToggle('superadmin', perm.key, $event)" />
                <div class="w-9 h-5 bg-slate-600 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-purple-500/50 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-slate-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-purple-600"></div>
              </label>
            </div>
          </div>
        </div>

        <!-- Garage Permissions -->
        <div class="bg-slate-800 rounded-xl border border-slate-700 p-6">
          <div class="flex items-center gap-3 mb-4">
            <div class="p-2 rounded-lg bg-cyan-500/10 text-cyan-400">
              <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8.25 18.75a1.5 1.5 0 01-3 0m3 0a1.5 1.5 0 00-3 0m3 0h6m-9 0H3.375a1.125 1.125 0 01-1.125-1.125V14.25m17.25 4.5a1.5 1.5 0 01-3 0m3 0a1.5 1.5 0 00-3 0m3 0h1.125c.621 0 1.129-.504 1.09-1.124a17.902 17.902 0 00-3.213-9.193 2.056 2.056 0 00-1.58-.86H14.25M16.5 18.75h-2.25m0-11.177v-.958c0-.568-.422-1.048-.987-1.106a48.554 48.554 0 00-10.026 0 1.106 1.106 0 00-.987 1.106v7.635m12-6.677v6.677m0 4.5v-4.5m0 0h-12" />
              </svg>
            </div>
            <h2 class="text-lg font-semibold text-white">{{ $t('permissions.garages') }}</h2>
          </div>
          <p class="text-sm text-slate-400 mb-4">{{ $t('permissions.garages_desc') }}</p>
          <div class="space-y-3">
            <div v-for="perm in garagePerms" :key="perm.key" class="flex items-center justify-between py-2 border-b border-slate-700/50 last:border-0">
              <span class="text-sm text-slate-300">{{ $t(`permissions.perms.${perm.key}`) }}</span>
              <label class="relative inline-flex items-center cursor-pointer">
                <input type="checkbox" :checked="isPermEnabled('garage', perm.key)" class="sr-only peer"
                  @change="handleToggle('garage', perm.key, $event)" />
                <div class="w-9 h-5 bg-slate-600 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-cyan-500/50 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-slate-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-cyan-600"></div>
              </label>
            </div>
          </div>
        </div>

        <!-- Package / Feature Flags -->
        <div class="bg-slate-800 rounded-xl border border-slate-700 p-6">
          <div class="flex items-center gap-3 mb-4">
            <div class="p-2 rounded-lg bg-amber-500/10 text-amber-400">
              <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20.25 7.5l-.625 10.632a2.25 2.25 0 01-2.247 2.118H6.622a2.25 2.25 0 01-2.247-2.118L3.75 7.5m8.25 3v6.75m0 0l-3-3m3 3l3-3M3.375 7.5h17.25c.621 0 1.125-.504 1.125-1.125v-1.5c0-.621-.504-1.125-1.125-1.125H3.375c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125z" />
              </svg>
            </div>
            <h2 class="text-lg font-semibold text-white">{{ $t('permissions.feature_flags') }}</h2>
          </div>
          <p class="text-sm text-slate-400 mb-4">{{ $t('permissions.feature_flags_desc', { tier: featureFlags.tier || 'free' }) }}</p>
          <div class="space-y-3">
            <div v-for="[key, granted] in featureEntries" :key="key" class="flex items-center justify-between py-2 border-b border-slate-700/50 last:border-0">
              <div class="flex flex-col">
                <span class="text-sm text-slate-300">{{ formatFeatureLabel(key) }}</span>
                <span class="text-xs text-slate-500">{{ key }}</span>
              </div>
              <label class="relative inline-flex items-center cursor-pointer">
                <input type="checkbox" :checked="granted" class="sr-only peer"
                  :disabled="true"
                  @change="handleToggle('feature', key, $event)" />
                <div class="w-9 h-5 bg-slate-600 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-amber-500/50 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-slate-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all"
                  :class="granted ? 'peer-checked:bg-amber-600' : ''"></div>
              </label>
            </div>
          </div>
        </div>
      </div>

      <!-- RBAC Permission Matrix -->
      <div class="bg-slate-800/50 border border-slate-700 rounded-xl p-6 mb-8">
        <h3 class="text-lg font-semibold text-white mb-4">{{ $t('permissions.rbac_title') }}</h3>
        <p class="text-sm text-slate-400 mb-6">{{ $t('permissions.rbac_desc') }}</p>

        <div class="overflow-x-auto">
          <table class="w-full text-sm">
            <thead>
              <tr class="border-b border-slate-700">
                <th class="text-left py-3 px-4 text-slate-400 font-medium">{{ $t('permissions.action') }}</th>
                <th v-for="role in permissionMatrix" :key="role.role" class="text-center py-3 px-4 text-slate-400 font-medium">
                  {{ role.role }}
                </th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="action in allActions" :key="action" class="border-b border-slate-700/50 hover:bg-slate-700/30">
                <td class="py-2.5 px-4 text-slate-300">{{ action }}</td>
                <td v-for="role in permissionMatrix" :key="role.role" class="text-center py-2.5 px-4">
                  <span v-if="hasPermission(role, action)" class="inline-flex items-center justify-center w-6 h-6 rounded-full bg-emerald-400/10">
                    <svg class="w-4 h-4 text-emerald-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
                    </svg>
                  </span>
                  <span v-else class="inline-flex items-center justify-center w-6 h-6 rounded-full bg-slate-700">
                    <svg class="w-4 h-4 text-slate-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                    </svg>
                  </span>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      <!-- Save Button (bottom) -->
      <div v-if="hasModifications" class="flex items-center gap-3 pb-8">
        <button @click="savePermissions"
          class="px-6 py-2.5 bg-emerald-600 hover:bg-emerald-500 text-white font-semibold rounded-lg shadow-lg shadow-emerald-600/20 transition-all hover:scale-[1.02] active:scale-[0.98] flex items-center gap-2">
          <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4" />
          </svg>
          {{ $t('permissions.save_changes') }}
        </button>
        <button @click="discardChanges"
          class="px-4 py-2.5 bg-slate-700 hover:bg-slate-600 text-slate-300 font-medium rounded-lg transition">
          {{ $t('permissions.discard') }}
        </button>
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'

definePageMeta({
  middleware: 'auth',
})

// ── State ──────────────────────────────────────────────────────────

const loading = ref(true)
const error = ref<string | null>(null)

interface FeatureFlagsResponse {
  tier: string
  features: Record<string, boolean>
  expires_at: string | null
}

interface PermissionMatrixEntry {
  role: string
  actions: string[]
}

interface PermissionMatrixResponse {
  matrix: PermissionMatrixEntry[]
  all_actions: string[]
}

const featureFlags = ref<FeatureFlagsResponse>({
  tier: 'free',
  features: {},
  expires_at: null,
})

const permissionMatrix = ref<PermissionMatrixEntry[]>([])
const allActions = ref<string[]>([])

// ── Editing State ───────────────────────────────────────────────────

// Track modified permissions: key = "group:permKey", value = boolean
const modifiedPermissions = ref<Map<string, boolean>>(new Map())

// Track original values for discard: key = "group:permKey", value = boolean
const originalPermissions = ref<Map<string, boolean>>(new Map())

// Save notification
const saveNotification = ref<{ type: 'success' | 'error'; message: string } | null>(null)

// ── Computed ───────────────────────────────────────────────────────

const featureEntries = computed(() => {
  return Object.entries(featureFlags.value.features || {})
})

const hasModifications = computed(() => {
  return modifiedPermissions.value.size > 0
})

const tierBadgeClass = computed(() => {
  const tier = featureFlags.value.tier
  if (tier === 'enterprise') return 'bg-purple-500/20 text-purple-300'
  if (tier === 'premium') return 'bg-amber-500/20 text-amber-300'
  return 'bg-slate-500/20 text-slate-300'
})

// Static permission definitions for the UI cards
const superadminPerms = [
  { key: 'user_mgmt', label: 'User Management', enabled: true },
  { key: 'billing_admin', label: 'Billing Administration', enabled: true },
  { key: 'robot_config', label: 'Robot Configuration', enabled: true },
  { key: 'system_logs', label: 'System Logs Access', enabled: true },
  { key: 'api_keys', label: 'API Key Management', enabled: false },
]

const garagePerms = [
  { key: 'vehicle_crud', label: 'Vehicle CRUD', enabled: true },
  { key: 'service_booking', label: 'Service Booking', enabled: true },
  { key: 'customer_view', label: 'Customer Data View', enabled: true },
  { key: 'report_export', label: 'Report Export', enabled: false },
  { key: 'bulk_import', label: 'Bulk Import', enabled: false },
]

// ── Methods ────────────────────────────────────────────────────────

/**
 * Check if a permission is currently enabled (considering modifications).
 */
function isPermEnabled(group: string, key: string): boolean {
  const mapKey = `${group}:${key}`
  // If modified, return the modified value
  if (modifiedPermissions.value.has(mapKey)) {
    return modifiedPermissions.value.get(mapKey)!
  }
  // Otherwise return the default
  const perms = group === 'superadmin' ? superadminPerms : garagePerms
  const perm = perms.find(p => p.key === key)
  return perm ? perm.enabled : false
}

function formatFeatureLabel(key: string): string {
  return key
    .replace(/^cost_category:/, '')
    .replace(/_/g, ' ')
    .replace(/\b\w/g, (c) => c.toUpperCase())
}

function formatDate(dateStr: string): string {
  try {
    const d = new Date(dateStr)
    return d.toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' })
  } catch {
    return dateStr
  }
}

function hasPermission(role: PermissionMatrixEntry, action: string): boolean {
  return role.actions.includes(action)
}

function handleToggle(group: string, key: string, event: Event) {
  const target = event.target as HTMLInputElement
  const newValue = target.checked
  const mapKey = `${group}:${key}`

  // Store original value if not already tracked
  if (!originalPermissions.value.has(mapKey)) {
    const perms = group === 'superadmin' ? superadminPerms : garagePerms
    const perm = perms.find(p => p.key === key)
    originalPermissions.value.set(mapKey, perm ? perm.enabled : false)
  }

  // Update modified state
  const originalValue = originalPermissions.value.get(mapKey)
  if (newValue === originalValue) {
    // Reverted to original — remove from modified
    modifiedPermissions.value.delete(mapKey)
  } else {
    modifiedPermissions.value.set(mapKey, newValue)
  }

  // Force reactivity by replacing the Map
  modifiedPermissions.value = new Map(modifiedPermissions.value)

  console.log(`[Permissions] Toggle: group=${group}, key=${key}, newValue=${newValue}`)
}

function clearSaveNotification() {
  setTimeout(() => {
    saveNotification.value = null
  }, 5000)
}

async function savePermissions() {
  saveNotification.value = null

  try {
    const tokenCookie = useCookie('access_token')
    const token = tokenCookie.value
    if (!token) {
      saveNotification.value = { type: 'error', message: 'Not authenticated' }
      clearSaveNotification()
      return
    }

    // Build payload: array of { action, granted }
    const payload: { action: string; granted: boolean }[] = []
    modifiedPermissions.value.forEach((granted, mapKey) => {
      // mapKey format: "superadmin:user_mgmt" or "garage:vehicle_crud"
      const action = mapKey.replace(/^(superadmin|garage):/, '').toUpperCase()
      payload.push({ action, granted })
    })

    if (payload.length === 0) {
      saveNotification.value = { type: 'error', message: 'No changes to save' }
      clearSaveNotification()
      return
    }

    // Send PATCH to the backend for each modified permission
    // We use the admin permissions override endpoint
    const results = await Promise.allSettled(
      payload.map(item =>
        $fetch('/api/v1/admin/permissions/override/0', {
          method: 'PATCH',
          headers: {
            Authorization: `Bearer ${token}`,
            'Content-Type': 'application/json',
          },
          body: {
            action: item.action,
            granted: item.granted,
          },
        })
      )
    )

    // Check for failures
    const failures = results.filter(r => r.status === 'rejected')
    if (failures.length > 0) {
      const errors = failures.map(f => (f as PromiseRejectedResult).reason?.message || 'Unknown error')
      saveNotification.value = {
        type: 'error',
        message: `Failed to save ${failures.length} permission(s): ${errors.join('; ')}`,
      }
      clearSaveNotification()
      return
    }

    // Success — clear modified state
    modifiedPermissions.value = new Map()
    originalPermissions.value = new Map()
    saveNotification.value = {
      type: 'success',
      message: `Successfully saved ${payload.length} permission change(s).`,
    }
    clearSaveNotification()

    console.log('[Permissions] Save successful:', payload)
  } catch (err: any) {
    console.error('[Permissions] Save failed:', err)
    saveNotification.value = {
      type: 'error',
      message: err?.message || 'Failed to save permissions',
    }
    clearSaveNotification()
  }
}

function discardChanges() {
  modifiedPermissions.value = new Map()
  originalPermissions.value = new Map()
  saveNotification.value = null
}

async function fetchFeatureFlags() {
  try {
    const tokenCookie = useCookie('access_token')
    const token = tokenCookie.value
    if (!token) {
      console.warn('[Permissions] No access token found for feature flags')
      return
    }

    const data = await $fetch<FeatureFlagsResponse>('/api/v1/subscriptions/feature-flags', {
      headers: { Authorization: `Bearer ${token}` },
    })
    console.log('[Permissions] Feature flags loaded:', data)
    featureFlags.value = data
  } catch (err: any) {
    console.error('[Permissions] Feature flags fetch failed:', err?.message || err)
    // Keep default values
  }
}

async function fetchPermissionMatrix() {
  try {
    const tokenCookie = useCookie('access_token')
    const token = tokenCookie.value
    if (!token) {
      console.warn('[Permissions] No access token found for permission matrix')
      return
    }

    const data = await $fetch<PermissionMatrixResponse>('/api/v1/admin/permissions/matrix', {
      headers: { Authorization: `Bearer ${token}` },
    })
    console.log('[Permissions] Permission matrix loaded:', data)
    permissionMatrix.value = data.matrix
    allActions.value = data.all_actions
  } catch (err: any) {
    console.error('[Permissions] Permission matrix fetch failed:', err?.message || err)
  }
}

async function fetchAll() {
  loading.value = true
  error.value = null
  try {
    await Promise.all([fetchFeatureFlags(), fetchPermissionMatrix()])
  } catch (err: any) {
    console.error('[Permissions] fetchAll failed:', err?.message || err)
    error.value = err?.message || 'Failed to load permissions data'
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchAll()
})
</script>
