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

interface RoleItem {
  id: number
  name: string
  permissions_count: number
  users_count: number
  is_protected: boolean
  created_at: string | null
}

interface Props {
  roles: RoleItem[]
}

defineOptions({ layout: AdminLayout })

const props = defineProps<Props>()

const deleteDialog = ref<boolean>(false)
const roleToDelete = ref<RoleItem | null>(null)

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',
    customer: 'default',
    billing_admin: 'warning',
    support_agent: 'info',
    support_lead: 'primary',
    readonly_admin: 'secondary',
  }
  return map[role] ?? 'default'
}

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

function confirmDelete(role: RoleItem): void {
  roleToDelete.value = role
  deleteDialog.value = true
}

function deleteRole(): void {
  if (!roleToDelete.value) return
  router.delete(`/staff/roles/${roleToDelete.value.id}`, {
    onFinish: () => {
      deleteDialog.value = false
      roleToDelete.value = null
    },
  })
}
</script>

<template>
  <div>
    <!-- Page 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">Role Management</span>
        </div>
        <div class="text-body-2 text-medium-emphasis ms-10">
          Configure roles and their permissions
        </div>
      </div>
      <Link href="/staff/roles/create" class="text-decoration-none">
        <VBtn
          color="primary"
          prepend-icon="tabler-plus"
        >
          Create Role
        </VBtn>
      </Link>
    </div>

    <!-- Roles Grid -->
    <VRow>
      <VCol
        v-for="role in roles"
        :key="role.id"
        cols="12"
        md="6"
        lg="4"
      >
        <VCard class="h-100">
          <VCardTitle class="d-flex align-center justify-space-between">
            <div class="d-flex align-center ga-2">
              <VChip
                :color="roleColor(role.name)"
                size="small"
                variant="tonal"
              >
                {{ formatRoleName(role.name) }}
              </VChip>
              <VChip
                v-if="role.is_protected"
                size="x-small"
                variant="outlined"
                color="warning"
              >
                Built-in
              </VChip>
            </div>
          </VCardTitle>
          <VCardText>
            <div class="d-flex justify-space-between align-center mb-3">
              <span class="text-body-2 text-medium-emphasis">Permissions</span>
              <VChip size="small" variant="tonal" color="info">
                {{ role.permissions_count }}
              </VChip>
            </div>
            <div class="d-flex justify-space-between align-center mb-3">
              <span class="text-body-2 text-medium-emphasis">Users</span>
              <VChip size="small" variant="tonal" color="primary">
                {{ role.users_count }}
              </VChip>
            </div>
            <div class="d-flex justify-space-between align-center">
              <span class="text-body-2 text-medium-emphasis">Created</span>
              <span class="text-body-2">{{ formatDate(role.created_at) }}</span>
            </div>
          </VCardText>
          <VDivider />
          <VCardActions class="justify-end pa-3">
            <Link :href="`/staff/roles/${role.id}/edit`" class="text-decoration-none">
              <VBtn
                variant="text"
                color="primary"
                size="small"
                prepend-icon="tabler-edit"
              >
                Edit
              </VBtn>
            </Link>
            <VBtn
              v-if="!role.is_protected"
              variant="text"
              color="error"
              size="small"
              prepend-icon="tabler-trash"
              :disabled="role.users_count > 0"
              @click="confirmDelete(role)"
            >
              Delete
            </VBtn>
          </VCardActions>
        </VCard>
      </VCol>
    </VRow>

    <!-- Empty State -->
    <VCard v-if="roles.length === 0" class="text-center py-12">
      <VCardText>
        <VIcon icon="tabler-lock-off" size="48" color="disabled" class="mb-2" />
        <div class="text-medium-emphasis mb-4">
          No roles found.
        </div>
        <Link href="/staff/roles/create" class="text-decoration-none">
          <VBtn color="primary" prepend-icon="tabler-plus">
            Create First Role
          </VBtn>
        </Link>
      </VCardText>
    </VCard>

    <!-- Delete Confirmation Dialog -->
    <VDialog v-model="deleteDialog" max-width="500">
      <VCard>
        <VCardTitle class="text-h6">
          Delete Role
        </VCardTitle>
        <VCardText>
          Are you sure you want to delete the role
          <strong>"{{ roleToDelete ? formatRoleName(roleToDelete.name) : '' }}"</strong>?
          This action cannot be undone.
        </VCardText>
        <VCardActions class="justify-end">
          <VBtn
            variant="text"
            @click="deleteDialog = false"
          >
            Cancel
          </VBtn>
          <VBtn
            color="error"
            variant="flat"
            @click="deleteRole"
          >
            Delete
          </VBtn>
        </VCardActions>
      </VCard>
    </VDialog>
  </div>
</template>
