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

interface StaffMember {
  id: number
  name: string
  email: string
  status: string
  role_names: string[]
  last_login_at: string | null
  last_login_ip: string | null
  created_at: string
}

interface RoleSummary {
  name: string
  users_count: number
}

interface Filters {
  search: string
  role: string
}

interface Props {
  staff: PaginatedResponse<StaffMember>
  roles: RoleSummary[]
  filters: Filters
}

defineOptions({ layout: AdminLayout })

const props = defineProps<Props>()

const search = ref<string>(props.filters.search)
const roleFilter = ref<string>(props.filters.role)

let searchTimeout: ReturnType<typeof setTimeout> | null = null

watch(search, (value: string) => {
  if (searchTimeout) {
    clearTimeout(searchTimeout)
  }
  searchTimeout = setTimeout(() => {
    applyFilters({ search: value })
  }, 400)
})

watch(roleFilter, (value: string) => {
  applyFilters({ role: value })
})

function applyFilters(overrides: Partial<Filters> = {}): void {
  router.get('/staff', {
    search: overrides.search ?? search.value,
    role: overrides.role ?? roleFilter.value,
  }, {
    preserveState: true,
    replace: true,
  })
}

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 formatRoleName(name: string): string {
  return name.replace(/_/g, ' ').replace(/\b\w/g, (c: string) => c.toUpperCase())
}

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

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

const roleOptions = [
  { title: 'All Roles', value: '' },
  ...props.roles.map((r: RoleSummary) => ({
    title: `${formatRoleName(r.name)} (${r.users_count})`,
    value: r.name,
  })),
]
</script>

<template>
  <div>
    <!-- Page Header -->
    <div class="d-flex align-center justify-space-between mb-6">
      <div>
        <div class="text-h4 font-weight-bold">
          Staff Management
        </div>
        <div class="text-body-2 text-medium-emphasis">
          Manage admin users and their roles
        </div>
      </div>
      <div class="d-flex ga-2">
        <Link href="/staff/roles" class="text-decoration-none">
          <VBtn
            variant="tonal"
            color="primary"
            prepend-icon="tabler-lock"
          >
            Manage Roles
          </VBtn>
        </Link>
      </div>
    </div>

    <!-- Filters -->
    <VCard class="mb-6">
      <VCardText>
        <VRow>
          <VCol cols="12" md="6">
            <VTextField
              v-model="search"
              prepend-inner-icon="tabler-search"
              placeholder="Search by name or email..."
              variant="outlined"
              density="compact"
              clearable
              hide-details
            />
          </VCol>
          <VCol cols="12" md="4">
            <VSelect
              v-model="roleFilter"
              :items="roleOptions"
              variant="outlined"
              density="compact"
              hide-details
              placeholder="Filter by role"
            />
          </VCol>
          <VCol cols="12" md="2" class="d-flex align-center">
            <VChip color="primary" variant="tonal" size="small">
              {{ staff.total }} staff
            </VChip>
          </VCol>
        </VRow>
      </VCardText>
    </VCard>

    <!-- Staff Table -->
    <VCard>
      <VCardText v-if="staff.data.length === 0" class="text-center py-12">
        <VIcon icon="tabler-shield-off" size="48" color="disabled" class="mb-2" />
        <div class="text-medium-emphasis">
          No staff members found.
        </div>
      </VCardText>

      <VTable v-else density="comfortable" hover>
        <thead>
          <tr>
            <th>Staff Member</th>
            <th>Roles</th>
            <th>Last Login</th>
            <th>Joined</th>
            <th class="text-end">
              Actions
            </th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="member in staff.data" :key="member.id">
            <td>
              <div class="d-flex align-center gap-3 py-2">
                <VAvatar color="primary" variant="tonal" size="38">
                  <span class="text-body-2 font-weight-medium">
                    {{ member.name.charAt(0).toUpperCase() }}
                  </span>
                </VAvatar>
                <div>
                  <div class="text-body-2 font-weight-medium">
                    {{ member.name }}
                  </div>
                  <div class="text-caption text-medium-emphasis">
                    {{ member.email }}
                  </div>
                </div>
              </div>
            </td>
            <td>
              <div class="d-flex flex-wrap ga-1">
                <VChip
                  v-for="role in member.role_names"
                  :key="role"
                  :color="roleColor(role)"
                  size="small"
                  variant="tonal"
                >
                  {{ formatRoleName(role) }}
                </VChip>
              </div>
            </td>
            <td>
              <div class="text-body-2">
                {{ formatDate(member.last_login_at) }}
              </div>
              <div v-if="member.last_login_ip" class="text-caption text-medium-emphasis">
                {{ member.last_login_ip }}
              </div>
            </td>
            <td class="text-body-2">
              {{ formatShortDate(member.created_at) }}
            </td>
            <td class="text-end">
              <Link
                :href="`/staff/${member.id}`"
                class="text-decoration-none"
              >
                <VBtn
                  variant="text"
                  color="primary"
                  size="small"
                >
                  <VIcon icon="tabler-eye" start />
                  View
                </VBtn>
              </Link>
            </td>
          </tr>
        </tbody>
      </VTable>

      <!-- Pagination -->
      <VCardText v-if="staff.last_page > 1" class="d-flex align-center justify-center pt-4">
        <VPagination
          :model-value="Math.ceil((staff.from || 1) / 20)"
          :length="staff.last_page"
          :total-visible="7"
          rounded
          @update:model-value="(page: number) => router.get('/staff', { ...props.filters, page }, { preserveState: true })"
        />
      </VCardText>
    </VCard>
  </div>
</template>
