<script lang="ts" setup>
import { Link } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import type { LoginHistoryEntry } from '@/types'

interface StaffMember {
  id: number
  name: string
  email: string
  status: string
  created_at: string
  roles: Array<{
    id: number
    name: string
    permissions: Array<{ id: number; name: string }>
  }>
}

interface Props {
  staffMember: StaffMember
  allPermissions: string[]
  directPermissions: string[]
  loginHistories: LoginHistoryEntry[]
}

defineOptions({ layout: AdminLayout })

const props = defineProps<Props>()

function formatRoleName(name: string): string {
  return name.replace(/_/g, ' ').replace(/\b\w/g, (c: string) => c.toUpperCase())
}

function roleColor(role: string): string {
  const map: Record<string, string> = {
    admin: 'error',
    super_admin: 'error',
    billing_admin: 'warning',
    support_agent: 'info',
    support_lead: 'primary',
    readonly_admin: 'secondary',
  }
  return map[role] ?? 'default'
}

function formatDate(dateStr: string): string {
  const date = new Date(dateStr)
  return date.toLocaleDateString('en-US', { month: 'short', day: '2-digit', year: 'numeric' })
}

function formatDateTime(dateStr: string): string {
  const date = new Date(dateStr)
  return date.toLocaleDateString('en-US', { month: 'short', day: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' })
}

function groupPermissions(permissions: string[]): Record<string, string[]> {
  const grouped: Record<string, string[]> = {}
  for (const perm of permissions) {
    if (perm.includes('.')) {
      const [group] = perm.split('.', 2)
      if (!grouped[group]) {
        grouped[group] = []
      }
      grouped[group].push(perm)
    }
    else {
      if (!grouped['legacy']) {
        grouped['legacy'] = []
      }
      grouped['legacy'].push(perm)
    }
  }
  return grouped
}

const groupedPermissions = groupPermissions(props.allPermissions)
</script>

<template>
  <div>
    <!-- Header -->
    <div class="d-flex align-center justify-space-between mb-6">
      <div>
        <div class="d-flex align-center gap-2 mb-1">
          <Link href="/staff" class="text-decoration-none">
            <VBtn icon="tabler-arrow-left" variant="text" size="small" />
          </Link>
          <span class="text-h4 font-weight-bold">{{ staffMember.name }}</span>
        </div>
        <div class="text-body-2 text-medium-emphasis ms-10">
          Staff member details and permissions
        </div>
      </div>
    </div>

    <VRow>
      <!-- Profile Card -->
      <VCol cols="12" md="4">
        <VCard class="mb-6">
          <VCardText class="text-center pt-8 pb-6">
            <VAvatar color="primary" variant="tonal" size="80" class="mb-4">
              <span class="text-h4 font-weight-medium">
                {{ staffMember.name.charAt(0).toUpperCase() }}
              </span>
            </VAvatar>
            <div class="text-h5 font-weight-bold mb-1">
              {{ staffMember.name }}
            </div>
            <div class="text-body-2 text-medium-emphasis mb-4">
              {{ staffMember.email }}
            </div>
            <div class="d-flex flex-wrap justify-center ga-1">
              <VChip
                v-for="role in staffMember.roles"
                :key="role.id"
                :color="roleColor(role.name)"
                size="small"
                variant="tonal"
              >
                {{ formatRoleName(role.name) }}
              </VChip>
            </div>
          </VCardText>
          <VDivider />
          <VCardText>
            <div class="d-flex justify-space-between align-center mb-2">
              <span class="text-body-2 text-medium-emphasis">Status</span>
              <VChip
                :color="staffMember.status === 'active' ? 'success' : 'error'"
                size="small"
                class="text-capitalize"
              >
                {{ staffMember.status }}
              </VChip>
            </div>
            <div class="d-flex justify-space-between align-center mb-2">
              <span class="text-body-2 text-medium-emphasis">Joined</span>
              <span class="text-body-2">{{ formatDate(staffMember.created_at) }}</span>
            </div>
            <div class="d-flex justify-space-between align-center">
              <span class="text-body-2 text-medium-emphasis">Permissions</span>
              <span class="text-body-2 font-weight-medium">{{ allPermissions.length }}</span>
            </div>
          </VCardText>
        </VCard>
      </VCol>

      <!-- Permissions & Login History -->
      <VCol cols="12" md="8">
        <!-- Permissions -->
        <VCard class="mb-6">
          <VCardTitle class="d-flex align-center justify-space-between">
            <span>Effective Permissions</span>
            <VChip color="primary" variant="tonal" size="small">
              {{ allPermissions.length }} total
            </VChip>
          </VCardTitle>
          <VCardText>
            <div v-if="allPermissions.length === 0" class="text-center py-4">
              <VIcon icon="tabler-lock-off" size="40" color="disabled" class="mb-2" />
              <div class="text-medium-emphasis">
                No permissions assigned.
              </div>
            </div>

            <div v-else>
              <div
                v-for="(perms, group) in groupedPermissions"
                :key="group"
                class="mb-4"
              >
                <div class="text-body-2 font-weight-bold text-capitalize mb-2">
                  {{ String(group).replace(/_/g, ' ') }}
                </div>
                <div class="d-flex flex-wrap ga-1">
                  <VChip
                    v-for="perm in perms"
                    :key="perm"
                    size="small"
                    variant="tonal"
                    color="success"
                  >
                    {{ perm }}
                  </VChip>
                </div>
              </div>
            </div>
          </VCardText>
        </VCard>

        <!-- Login History -->
        <VCard>
          <VCardTitle>Recent Login History</VCardTitle>
          <VCardText v-if="loginHistories.length === 0" class="text-center py-4">
            <VIcon icon="tabler-history-off" size="40" color="disabled" class="mb-2" />
            <div class="text-medium-emphasis">
              No login history found.
            </div>
          </VCardText>

          <VTable v-else density="compact">
            <thead>
              <tr>
                <th>Date</th>
                <th>IP Address</th>
                <th>Device</th>
                <th>Location</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="entry in loginHistories" :key="entry.id">
                <td class="text-body-2">
                  {{ formatDateTime(entry.created_at) }}
                </td>
                <td class="text-body-2">
                  {{ entry.ip_address }}
                </td>
                <td class="text-body-2">
                  <span v-if="entry.browser || entry.os">
                    {{ entry.browser }} / {{ entry.os }}
                  </span>
                  <span v-else class="text-medium-emphasis">Unknown</span>
                </td>
                <td class="text-body-2">
                  <span v-if="entry.location_city || entry.location_country">
                    {{ [entry.location_city, entry.location_country].filter(Boolean).join(', ') }}
                  </span>
                  <span v-else class="text-medium-emphasis">Unknown</span>
                </td>
                <td>
                  <VChip
                    :color="entry.success ? 'success' : 'error'"
                    size="x-small"
                  >
                    {{ entry.success ? 'Success' : 'Failed' }}
                  </VChip>
                </td>
              </tr>
            </tbody>
          </VTable>
        </VCard>
      </VCol>
    </VRow>
  </div>
</template>
