<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useApi } from '@/composables/useApi'
import Panel from '@/components/ds/data/Panel.vue'
import Button from '@/components/ds/core/Button.vue'
import IconButton from '@/components/ds/core/IconButton.vue'
import Badge from '@/components/ds/core/Badge.vue'
import Icon from '@/components/ds/core/Icon.vue'
import Input from '@/components/ds/forms/Input.vue'
import EmptyState from '@/components/ds/feedback/EmptyState.vue'

const api = useApi()

interface PlatformUser {
  id: string
  email: string
  username: string
  is_super_admin: boolean
  email_verified: boolean
  license_count: number
  created_at: string
  last_login_at: string | null
}

const users = ref<PlatformUser[]>([])
const isLoading = ref(false)
const searchQuery = ref('')
const page = ref(1)
const perPage = 25
const total = ref(0)

const totalPages = computed(() => Math.max(1, Math.ceil(total.value / perPage)))

function formatDate(iso: string): string {
  return new Date(iso).toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
  })
}

function formatLastLogin(iso: string | null): string {
  if (!iso) return 'Never'
  const diff = Date.now() - new Date(iso).getTime()
  const minutes = Math.floor(diff / 60000)
  const hours = Math.floor(minutes / 60)
  const days = Math.floor(hours / 24)
  if (minutes < 1) return 'Just now'
  if (minutes < 60) return `${minutes}m ago`
  if (hours < 24) return `${hours}h ago`
  if (days < 7) return `${days}d ago`
  return formatDate(iso)
}

async function fetchUsers() {
  isLoading.value = true
  try {
    const params = new URLSearchParams({
      page: page.value.toString(),
      per_page: perPage.toString(),
    })
    if (searchQuery.value.trim()) params.set('search', searchQuery.value.trim())

    const data = await api.get<{ data: PlatformUser[]; total: number }>(`/admin/users?${params}`)
    users.value = data.data
    total.value = data.total
  } catch {
    // API not wired yet
  } finally {
    isLoading.value = false
  }
}

async function toggleSuperAdmin(user: PlatformUser) {
  const action = user.is_super_admin ? 'remove super admin from' : 'grant super admin to'
  if (!confirm(`Are you sure you want to ${action} ${user.email}?`)) return
  try {
    await api.request(`/admin/users/${user.id}`, {
      method: 'PATCH',
      body: { is_super_admin: !user.is_super_admin },
    })
    user.is_super_admin = !user.is_super_admin
  } catch {
    // Handle error
  }
}

async function disableAccount(user: PlatformUser) {
  if (!confirm(`Are you sure you want to disable the account for ${user.email}? This cannot be undone from this panel.`)) return
  try {
    await api.request(`/admin/users/${user.id}`, {
      method: 'PATCH',
      body: { disabled: true },
    })
    await fetchUsers()
  } catch {
    // Handle error
  }
}

function prevPage() {
  if (page.value > 1) page.value--
}

function nextPage() {
  if (page.value < totalPages.value) page.value++
}

watch(searchQuery, () => {
  page.value = 1
})

watch([page, searchQuery], () => {
  fetchUsers()
})

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

<template>
  <div class="pau">
    <!-- Page head -->
    <div class="pau__head">
      <div class="pau__head-id">
        <div class="pau__chip">
          <Icon name="users" :size="20" :stroke-width="2" />
        </div>
        <div>
          <div class="t-eyebrow">Platform admin</div>
          <h1 class="pau__title">User management</h1>
        </div>
      </div>
    </div>

    <!-- Search -->
    <div class="pau__filters">
      <Input
        v-model="searchQuery"
        placeholder="Search by email or username"
        icon="search"
        style="flex: 1; max-width: 360px"
      />
    </div>

    <!-- Table -->
    <Panel :flush-body="true" :subtitle="total + ' registered users'">
      <table class="pau__table">
        <thead>
          <tr class="pau__thead-row">
            <th class="pau__th">Email</th>
            <th class="pau__th">Username</th>
            <th class="pau__th">Super admin</th>
            <th class="pau__th">Licenses</th>
            <th class="pau__th">Created</th>
            <th class="pau__th">Last login</th>
            <th class="pau__th pau__th--right">Actions</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="isLoading">
            <td colspan="7" class="pau__td-empty">Loading users...</td>
          </tr>
          <tr v-else-if="users.length === 0">
            <td colspan="7" class="pau__td-es">
              <EmptyState
                icon="users"
                :title="searchQuery ? 'No matching users' : 'No users found'"
                :description="searchQuery ? 'Try a different search term.' : 'Registered users will appear here.'"
              />
            </td>
          </tr>
          <tr
            v-for="user in users"
            :key="user.id"
            class="pau__tr"
            :class="{ 'pau__tr--disabled': false }"
          >
            <td class="pau__td">{{ user.email }}</td>
            <td class="pau__td pau__td--secondary">{{ user.username }}</td>
            <td class="pau__td">
              <Badge v-if="user.is_super_admin" tone="accent" icon="shield">Super admin</Badge>
              <span v-else class="pau__empty-cell">—</span>
            </td>
            <td class="pau__td pau__td--mono">{{ user.license_count }}</td>
            <td class="pau__td pau__td--secondary">{{ formatDate(user.created_at) }}</td>
            <td class="pau__td pau__td--secondary">{{ formatLastLogin(user.last_login_at) }}</td>
            <td class="pau__td pau__td--actions">
              <div class="pau__actions">
                <IconButton
                  :icon="user.is_super_admin ? 'shield' : 'shield'"
                  :variant="user.is_super_admin ? 'accent' : 'ghost'"
                  size="sm"
                  :label="user.is_super_admin ? 'Remove super admin' : 'Grant super admin'"
                  :disabled="false"
                  @click="toggleSuperAdmin(user)"
                />
                <IconButton
                  icon="ban"
                  variant="ghost"
                  size="sm"
                  label="Disable account"
                  :disabled="false"
                  @click="disableAccount(user)"
                />
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </Panel>

    <!-- Pagination -->
    <div class="pau__pager">
      <span class="pau__pager-info">Page {{ page }} of {{ totalPages }}</span>
      <div class="pau__pager-btns">
        <Button variant="secondary" size="sm" icon="chevron-left" :disabled="page <= 1" @click="prevPage">Prev</Button>
        <Button variant="secondary" size="sm" icon-right="chevron-right" :disabled="page >= totalPages" @click="nextPage">Next</Button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.pau { max-width: 1200px; margin: 0 auto; display: flex; flex-direction: column; gap: 16px; }

/* Page head */
.pau__head { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 12px; }
.pau__head-id { display: flex; align-items: center; gap: 12px; }
.pau__chip {
  width: 40px; height: 40px; flex: none; border-radius: var(--radius-md);
  display: flex; align-items: center; justify-content: center;
  color: var(--accent); background: var(--accent-soft);
  box-shadow: inset 0 0 0 1px var(--accent-border);
}
.pau__title {
  font-size: var(--text-2xl); font-weight: 700; letter-spacing: -0.02em;
  color: var(--text-primary); margin-top: 3px;
}

/* Filters */
.pau__filters { display: flex; align-items: center; gap: 10px; }

/* Table */
.pau__table { width: 100%; border-collapse: collapse; }
.pau__thead-row { border-bottom: 1px solid var(--border-subtle); }
.pau__th {
  padding: 10px 16px; text-align: left;
  font-size: var(--text-xs); font-weight: 600; color: var(--text-tertiary);
  text-transform: uppercase; letter-spacing: var(--tracking-wider);
  white-space: nowrap;
}
.pau__th--right { text-align: right; }
.pau__tr { border-bottom: 1px solid var(--border-subtle); transition: var(--transition-colors); }
.pau__tr:last-child { border-bottom: 0; }
.pau__tr:hover { background: var(--surface-hover); }
.pau__td { padding: 11px 16px; font-size: var(--text-sm); color: var(--text-primary); }
.pau__td--secondary { color: var(--text-secondary); }
.pau__td--mono { font-family: var(--font-mono); font-variant-numeric: tabular-nums; font-size: var(--text-xs); color: var(--text-secondary); }
.pau__td--actions { text-align: right; }
.pau__td-empty { padding: 12px 16px; text-align: center; font-size: var(--text-sm); color: var(--text-tertiary); }
.pau__td-es { padding: 0; }

.pau__empty-cell { font-size: var(--text-sm); color: var(--text-muted); }

/* Actions */
.pau__actions { display: inline-flex; align-items: center; gap: 2px; }

/* Pagination */
.pau__pager { display: flex; align-items: center; justify-content: space-between; }
.pau__pager-info { font-size: var(--text-sm); color: var(--text-tertiary); font-family: var(--font-mono); font-variant-numeric: tabular-nums; }
.pau__pager-btns { display: flex; align-items: center; gap: 8px; }
</style>
