<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('common.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('common.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>

      <!-- ── DUAL FILTERING: Domain (Row) Filter + Role (Column) Filter ── -->
      <div class="bg-slate-800/60 border border-slate-700 rounded-xl p-4 mb-6">
        <div class="flex flex-col sm:flex-row sm:items-center gap-4">
          <!-- Filter 1: Domain/Row Filter (Tab Group) -->
          <div class="flex-1">
            <label class="block text-xs font-semibold uppercase tracking-wider text-slate-400 mb-2">
              {{ $t('permissions.domain_filter') }}
            </label>
            <div class="flex flex-wrap gap-1.5">
              <button
                v-for="domain in domainOptions"
                :key="domain.value"
                @click="activeDomain = domain.value"
                class="px-3 py-1.5 text-xs font-medium rounded-lg transition"
                :class="activeDomain === domain.value
                  ? 'bg-indigo-600 text-white shadow-sm'
                  : 'bg-slate-700/60 text-slate-400 hover:bg-slate-700 hover:text-white'"
              >
                {{ domain.label }}
              </button>
            </div>
          </div>

          <!-- Filter 2: Role/Column Filter (Multi-select Pills) -->
          <div class="flex-1">
            <label class="block text-xs font-semibold uppercase tracking-wider text-slate-400 mb-2">
              {{ $t('permissions.role_filter') }}
            </label>
            <div class="flex flex-wrap gap-1.5">
              <button
                v-for="role in roles"
                :key="role.id"
                @click="toggleRoleFilter(role.id)"
                class="px-3 py-1.5 text-xs font-medium rounded-lg transition flex items-center gap-1.5"
                :class="filteredRoleIds.has(role.id)
                  ? role.rank >= 100
                    ? 'bg-purple-600/30 text-purple-300 border border-purple-500/30'
                    : 'bg-indigo-600/30 text-indigo-300 border border-indigo-500/30'
                  : 'bg-slate-700/60 text-slate-500 hover:bg-slate-700 hover:text-slate-300 border border-transparent'"
              >
                <!-- Check icon when selected -->
                <svg v-if="filteredRoleIds.has(role.id)" class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M5 13l4 4L19 7" />
                </svg>
                <span>{{ role.name }}</span>
              </button>
            </div>
            <!-- Quick toggle all -->
            <div class="mt-2 flex gap-2">
              <button @click="selectAllRoles" class="text-xs text-indigo-400 hover:text-indigo-300 transition">
                {{ $t('common.select_all') }}
              </button>
              <button @click="deselectAllRoles" class="text-xs text-slate-500 hover:text-slate-400 transition">
                {{ $t('common.deselect_all') }}
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- ── STICKY SAVE BUTTON ── -->
      <div v-if="hasModifications" class="sticky top-0 z-20 -mx-4 px-4 py-3 bg-slate-800/95 backdrop-blur-sm border-b border-slate-700 mb-4 flex items-center gap-3 rounded-t-xl">
        <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('common.discard') }}
        </button>
        <span class="text-sm text-slate-400 ml-auto">
          {{ $t('permissions.modified_count', { count: modifiedRoles.size }) }}
        </span>
      </div>

      <!-- ── 2D PERMISSION MATRIX TABLE ── -->
      <div class="overflow-x-auto rounded-xl border border-slate-700 bg-slate-800/40">
        <table class="w-full text-sm">
          <!-- Table Header: Roles as Columns -->
          <thead>
            <tr class="border-b border-slate-700">
              <!-- Top-left blank cell -->
              <th class="sticky left-0 z-10 bg-slate-800/95 min-w-[200px] p-3 text-left">
                <div class="flex items-center gap-2">
                  <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="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                  </svg>
                  <span class="text-xs font-semibold uppercase tracking-wider text-slate-400">
                    {{ $t('common.permission') }}
                  </span>
                </div>
              </th>
              <!-- Role columns -->
              <th
                v-for="role in filteredRoles"
                :key="role.id"
                class="min-w-[120px] p-3 text-center border-l border-slate-700"
                :class="role.rank >= 100 ? 'bg-purple-900/10' : ''"
              >
                <div class="flex flex-col items-center gap-1">
                  <span
                    class="text-xs font-semibold px-2 py-0.5 rounded-full"
                    :class="roleHeaderClass(role)"
                  >
                    {{ role.name }}
                  </span>
                  <span class="text-[10px] text-slate-500">Rank {{ role.rank }}</span>
                  <span v-if="role.is_system" class="text-[10px] text-indigo-400">system</span>
                </div>
              </th>
            </tr>
          </thead>

          <!-- Table Body: Permissions as Rows -->
          <tbody>
            <!-- Domain group separator -->
            <template v-for="domain in filteredDomains" :key="domain">
              <!-- Domain header row -->
              <tr class="border-b border-slate-700/50">
                <td
                  colspan="1"
                  class="sticky left-0 z-10 bg-slate-800/95 px-3 py-2 text-xs font-bold uppercase tracking-wider"
                  :class="domainColorClass(domain)"
                >
                  <div class="flex items-center gap-2">
                    <span>{{ domain }}</span>
                    <span class="text-[10px] text-slate-500 font-normal normal-case">
                      ({{ getDomainPermissions(domain).length }})
                    </span>
                  </div>
                </td>
                <!-- Fill remaining columns with the same background -->
                <td
                  v-for="role in filteredRoles"
                  :key="'hdr-' + role.id"
                  class="border-l border-slate-700/50 bg-slate-800/60 px-3 py-2"
                ></td>
              </tr>

              <!-- Permission rows for this domain -->
              <tr
                v-for="perm in getDomainPermissions(domain)"
                :key="perm.id"
                class="border-b border-slate-700/30 hover:bg-slate-700/20 transition"
              >
                <!-- Permission label (sticky left column) -->
                <td class="sticky left-0 z-10 bg-slate-800/95 p-3 border-r border-slate-700/50">
                  <div class="flex flex-col min-w-0 max-w-[200px]">
                    <span class="text-sm text-slate-200 truncate font-medium">{{ formatPermissionLabel(perm) }}</span>
                    <span class="text-xs text-slate-500 truncate font-mono">{{ perm.code }}</span>
                    <span v-if="perm.description" class="text-[11px] text-slate-500 truncate mt-0.5">{{ perm.description }}</span>
                  </div>
                </td>

                <!-- Checkbox cells for each role -->
                <td
                  v-for="role in filteredRoles"
                  :key="'cell-' + role.id + '-' + perm.id"
                  class="p-3 text-center border-l border-slate-700/30"
                  :class="getCellClass(role, perm)"
                >
                  <label
                    class="relative inline-flex items-center justify-center"
                    :class="isRoleLocked(role)
                      ? 'cursor-not-allowed'
                      : 'cursor-pointer'"
                  >
                    <input
                      type="checkbox"
                      :checked="isPermEnabled(role.id, perm.id)"
                      class="sr-only peer"
                      :disabled="isRoleLocked(role)"
                      @change="handleToggle(role.id, perm.id, $event)"
                    />
                    <!-- Toggle track -->
                    <div
                      class="w-9 h-5 rounded-full transition-all duration-200 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 after:duration-200"
                      :class="getToggleClass(role, perm)"
                    ></div>
                  </label>
                </td>
              </tr>
            </template>

            <!-- Empty state -->
            <tr v-if="filteredPermissions.length === 0">
              <td :colspan="filteredRoles.length + 1" class="p-8 text-center text-slate-500 text-sm">
                {{ $t('permissions.no_permissions') }}
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- Bottom Save Button -->
      <div v-if="hasModifications" class="mt-6 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('common.discard') }}
        </button>
        <span class="text-sm text-slate-400">
          {{ $t('permissions.modified_count', { count: modifiedRoles.size }) }}
        </span>
      </div>
    </template>
  </div>
</template>

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

definePageMeta({
  middleware: 'auth',
})

// ── Types ──────────────────────────────────────────────────────────

interface SystemRole {
  id: number
  name: string
  description: string | null
  rank: number
  is_system: boolean
  is_active: boolean
  permission_ids: number[]
}

interface SystemPermission {
  id: number
  code: string
  domain: string
  action: string
  description: string | null
  is_system: boolean
}

interface DomainOption {
  value: string
  label: string
}

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

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

const roles = ref<SystemRole[]>([])
const permissions = ref<SystemPermission[]>([])

// ── Filter State ───────────────────────────────────────────────────

const activeDomain = ref<string>('__all__')
const filteredRoleIds = ref<Set<number>>(new Set())

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

const modifiedRoles = ref<Map<number, Set<number>>>(new Map())
const originalPermissions = ref<Map<number, number[]>>(new Map())
const saveNotification = ref<{ type: 'success' | 'error'; message: string } | null>(null)

// ── Computed: Domain Options ───────────────────────────────────────

const domainOptions = computed<DomainOption[]>(() => {
  const domains = new Set(permissions.value.map(p => p.domain))
  const options: DomainOption[] = [
    { value: '__all__', label: $t('permissions.all_domains') },
  ]
  for (const domain of Array.from(domains).sort()) {
    options.push({ value: domain, label: domain.charAt(0).toUpperCase() + domain.slice(1) })
  }
  return options
})

// ── Computed: Filtered Domains (for table section headers) ─────────

const filteredDomains = computed<string[]>(() => {
  const domains = new Set(permissions.value.map(p => p.domain))
  const sorted = Array.from(domains).sort()
  if (activeDomain.value === '__all__') return sorted
  return sorted.filter(d => d === activeDomain.value)
})

// ── Computed: Filtered Permissions ─────────────────────────────────

const filteredPermissions = computed<SystemPermission[]>(() => {
  if (activeDomain.value === '__all__') return permissions.value
  return permissions.value.filter(p => p.domain === activeDomain.value)
})

// ── Computed: Filtered Roles ───────────────────────────────────────

const filteredRoles = computed<SystemRole[]>(() => {
  if (filteredRoleIds.value.size === 0) return roles.value
  return roles.value.filter(r => filteredRoleIds.value.has(r.id))
})

// ── Computed: Has Modifications ────────────────────────────────────

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

// ── Methods: Filter Helpers ────────────────────────────────────────

function toggleRoleFilter(roleId: number) {
  const newSet = new Set(filteredRoleIds.value)
  if (newSet.has(roleId)) {
    newSet.delete(roleId)
  } else {
    newSet.add(roleId)
  }
  filteredRoleIds.value = newSet
}

function selectAllRoles() {
  filteredRoleIds.value = new Set(roles.value.map(r => r.id))
}

function deselectAllRoles() {
  filteredRoleIds.value = new Set()
}

// ── Methods: UI Helpers ────────────────────────────────────────────

function roleHeaderClass(role: SystemRole): string {
  if (role.rank >= 100) return 'bg-purple-500/20 text-purple-300'
  if (role.rank >= 80) return 'bg-indigo-500/20 text-indigo-300'
  if (role.rank >= 50) return 'bg-cyan-500/20 text-cyan-300'
  return 'bg-slate-500/20 text-slate-300'
}

function domainColorClass(domain: string): string {
  const colorMap: Record<string, string> = {
    fleet: 'text-emerald-400',
    user: 'text-sky-400',
    finance: 'text-amber-400',
    permissions: 'text-purple-400',
    system: 'text-rose-400',
    service: 'text-teal-400',
    organization: 'text-orange-400',
    vehicle: 'text-cyan-400',
    subscription: 'text-pink-400',
    moderation: 'text-violet-400',
  }
  return colorMap[domain] || 'text-slate-400'
}

function getCellClass(role: SystemRole, perm: SystemPermission): string {
  if (isRoleLocked(role)) {
    return isPermEnabled(role.id, perm.id) ? 'bg-purple-900/10' : 'bg-purple-900/5'
  }
  if (isPermEnabled(role.id, perm.id)) return 'bg-emerald-900/10'
  return ''
}

function formatPermissionLabel(perm: SystemPermission): string {
  return perm.code
    .replace(/:/g, ' ')
    .replace(/\b\w/g, (c) => c.toUpperCase())
}

function getToggleClass(role: SystemRole, perm: SystemPermission): string {
  const enabled = isPermEnabled(role.id, perm.id)
  const locked = isRoleLocked(role)

  // Base classes: circle position
  const baseClasses = 'peer-focus:outline-none peer-focus:ring-2'

  if (locked) {
    // SUPERADMIN: show ON (green) when enabled, OFF (gray) when disabled — but always unclickable
    if (enabled) {
      return `${baseClasses} bg-emerald-600 peer-focus:ring-emerald-500/50 after:translate-x-full after:border-white`
    }
    return `${baseClasses} bg-slate-600`
  }

  // Interactive toggles: use peer-checked for dynamic behavior
  if (enabled) {
    return `${baseClasses} bg-emerald-600 peer-focus:ring-emerald-500/50 peer-checked:after:translate-x-full peer-checked:after:border-white`
  }
  return `${baseClasses} bg-slate-600 peer-focus:ring-indigo-500/50 peer-checked:after:translate-x-full peer-checked:after:border-white peer-checked:bg-indigo-600`
}

function getDomainPermissions(domain: string): SystemPermission[] {
  return filteredPermissions.value.filter(p => p.domain === domain)
}

// ── Methods: Permission Toggle Logic ───────────────────────────────

function isPermEnabled(roleId: number, permissionId: number): boolean {
  if (modifiedRoles.value.has(roleId)) {
    const rolePerms = modifiedRoles.value.get(roleId)!
    return rolePerms.has(permissionId)
  }
  const role = roles.value.find(r => r.id === roleId)
  return role ? role.permission_ids.includes(permissionId) : false
}

function isRoleLocked(role: SystemRole): boolean {
  return role.is_system && role.rank >= 100
}

function handleToggle(roleId: number, permissionId: number, event: Event) {
  const target = event.target as HTMLInputElement
  const newValue = target.checked

  if (!originalPermissions.value.has(roleId)) {
    const role = roles.value.find(r => r.id === roleId)
    if (role) {
      originalPermissions.value.set(roleId, [...role.permission_ids])
    }
  }

  let rolePerms = modifiedRoles.value.get(roleId)
  if (!rolePerms) {
    const original = originalPermissions.value.get(roleId) || []
    rolePerms = new Set(original)
  } else {
    rolePerms = new Set(rolePerms)
  }

  if (newValue) {
    rolePerms.add(permissionId)
  } else {
    rolePerms.delete(permissionId)
  }

  const original = originalPermissions.value.get(roleId) || []
  const originalSet = new Set(original)

  if (setsEqual(rolePerms, originalSet)) {
    modifiedRoles.value.delete(roleId)
    originalPermissions.value.delete(roleId)
  } else {
    modifiedRoles.value.set(roleId, rolePerms)
  }

  modifiedRoles.value = new Map(modifiedRoles.value)
}

function setsEqual(a: Set<number>, b: Set<number>): boolean {
  if (a.size !== b.size) return false
  for (const item of a) {
    if (!b.has(item)) return false
  }
  return true
}

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

// ── Methods: Save / Discard ────────────────────────────────────────

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
    }

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

    const updates: { roleId: number; permissionIds: number[] }[] = []
    modifiedRoles.value.forEach((permSet, roleId) => {
      updates.push({
        roleId,
        permissionIds: Array.from(permSet).sort((a, b) => a - b),
      })
    })

    const results = await Promise.allSettled(
      updates.map(update =>
        $fetch(`/api/v1/admin/permissions/roles/${update.roleId}/permissions`, {
          method: 'PUT',
          headers: {
            Authorization: `Bearer ${token}`,
            'Content-Type': 'application/json',
          },
          body: {
            permission_ids: update.permissionIds,
          },
        })
      )
    )

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

    for (const update of updates) {
      const role = roles.value.find(r => r.id === update.roleId)
      if (role) {
        role.permission_ids = update.permissionIds
      }
    }

    modifiedRoles.value = new Map()
    originalPermissions.value = new Map()
    saveNotification.value = {
      type: 'success',
      message: `Successfully saved permissions for ${updates.length} role(s).`,
    }
    clearSaveNotification()
  } catch (err: any) {
    console.error('[Permissions] Save failed:', err)
    saveNotification.value = {
      type: 'error',
      message: err?.data?.detail || err?.message || 'Failed to save permissions',
    }
    clearSaveNotification()
  }
}

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

// ── Data Fetching ──────────────────────────────────────────────────

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

    const data = await $fetch<SystemRole[]>('/api/v1/admin/permissions/roles', {
      headers: { Authorization: `Bearer ${token}` },
    })
    roles.value = data
  } catch (err: any) {
    console.error('[Permissions] Roles fetch failed:', err?.message || err)
    throw err
  }
}

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

    const data = await $fetch<SystemPermission[]>('/api/v1/admin/permissions', {
      headers: { Authorization: `Bearer ${token}` },
    })
    permissions.value = data
  } catch (err: any) {
    console.error('[Permissions] Permissions fetch failed:', err?.message || err)
    throw err
  }
}

async function fetchAll() {
  loading.value = true
  error.value = null
  try {
    await Promise.all([fetchRoles(), fetchPermissions()])
    // Initialize: show all roles by default
    filteredRoleIds.value = new Set(roles.value.map(r => r.id))
  } catch (err: any) {
    console.error('[Permissions] fetchAll failed:', err?.message || err)
    error.value = err?.data?.detail || err?.message || 'Failed to load permissions data'
  } finally {
    loading.value = false
  }
}

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