<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useApi } from '@/composables/useApi'
import { Users, Search, ShieldCheck, ShieldOff, UserX, ChevronLeft, ChevronRight } from 'lucide-vue-next'

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="p-6 space-y-6 bg-neutral-950 min-h-screen">
    <!-- Header -->
    <div class="flex items-center gap-3">
      <Users class="w-5 h-5 text-oxide-500" />
      <div>
        <h1 class="text-2xl font-bold text-neutral-100">User Management</h1>
        <p class="text-sm text-neutral-400 mt-0.5">{{ total }} registered users</p>
      </div>
    </div>

    <!-- Search -->
    <div class="flex items-center gap-4">
      <div class="relative flex-1 max-w-sm">
        <Search class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-neutral-500" />
        <input
          v-model="searchQuery"
          type="text"
          placeholder="Search by email or username..."
          class="w-full pl-10 pr-3 py-2 bg-neutral-800 border border-neutral-700 rounded-lg text-sm text-neutral-100 placeholder-neutral-500 focus:outline-none focus:ring-2 focus:ring-oxide-500/50 focus:border-oxide-500 transition-colors"
        />
      </div>
    </div>

    <!-- Table -->
    <div class="bg-neutral-900 border border-neutral-800 rounded-lg overflow-hidden">
      <table class="w-full">
        <thead>
          <tr class="border-b border-neutral-800 text-left">
            <th class="px-4 py-3 text-xs font-medium text-neutral-500 uppercase tracking-wider">Email</th>
            <th class="px-4 py-3 text-xs font-medium text-neutral-500 uppercase tracking-wider">Username</th>
            <th class="px-4 py-3 text-xs font-medium text-neutral-500 uppercase tracking-wider">Super Admin</th>
            <th class="px-4 py-3 text-xs font-medium text-neutral-500 uppercase tracking-wider">Licenses</th>
            <th class="px-4 py-3 text-xs font-medium text-neutral-500 uppercase tracking-wider">Created</th>
            <th class="px-4 py-3 text-xs font-medium text-neutral-500 uppercase tracking-wider">Last Login</th>
            <th class="px-4 py-3 text-xs font-medium text-neutral-500 uppercase tracking-wider text-right">Actions</th>
          </tr>
        </thead>
        <tbody class="divide-y divide-neutral-800">
          <tr v-if="users.length === 0 && !isLoading">
            <td colspan="7" class="px-4 py-12 text-center text-neutral-500 text-sm">
              <template v-if="searchQuery">No users matching "{{ searchQuery }}"</template>
              <template v-else>No users found.</template>
            </td>
          </tr>
          <tr v-if="isLoading">
            <td colspan="7" class="px-4 py-12 text-center text-neutral-500 text-sm">Loading users...</td>
          </tr>
          <tr
            v-for="user in users"
            :key="user.id"
            class="hover:bg-neutral-800/50 transition-colors"
            :class="{ 'opacity-50': false }"
          >
            <td class="px-4 py-3 text-sm text-neutral-100">{{ user.email }}</td>
            <td class="px-4 py-3 text-sm text-neutral-400">{{ user.username }}</td>
            <td class="px-4 py-3">
              <span
                v-if="user.is_super_admin"
                class="inline-flex items-center gap-1.5 text-xs font-medium px-2 py-0.5 rounded-full bg-oxide-500/10 text-oxide-400"
              >
                <ShieldCheck class="w-3 h-3" />
                Super Admin
              </span>
              <span v-else class="text-xs text-neutral-600">&mdash;</span>
            </td>
            <td class="px-4 py-3 text-sm text-neutral-400">{{ user.license_count }}</td>
            <td class="px-4 py-3 text-sm text-neutral-400">{{ formatDate(user.created_at) }}</td>
            <td class="px-4 py-3 text-sm text-neutral-400">{{ formatLastLogin(user.last_login_at) }}</td>
            <td class="px-4 py-3 text-right">
              <div class="flex items-center justify-end gap-1">
                <button
                  @click="toggleSuperAdmin(user)"
                  :disabled="false"
                  class="p-1.5 rounded transition-colors"
                  :class="user.is_super_admin
                    ? 'text-oxide-400 hover:text-oxide-300 hover:bg-oxide-500/10'
                    : 'text-neutral-500 hover:text-neutral-300 hover:bg-neutral-700'"
                  :title="user.is_super_admin ? 'Remove Super Admin' : 'Grant Super Admin'"
                >
                  <ShieldCheck v-if="!user.is_super_admin" class="w-4 h-4" />
                  <ShieldOff v-else class="w-4 h-4" />
                </button>
                <button
                  @click="disableAccount(user)"
                  :disabled="false"
                  class="p-1.5 text-neutral-500 hover:text-red-400 hover:bg-red-500/10 disabled:opacity-30 disabled:cursor-not-allowed rounded transition-colors"
                  title="Disable Account"
                >
                  <UserX class="w-4 h-4" />
                </button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- Pagination -->
    <div class="flex items-center justify-between">
      <p class="text-sm text-neutral-500">
        Page {{ page }} of {{ totalPages }}
      </p>
      <div class="flex items-center gap-2">
        <button
          @click="prevPage"
          :disabled="page <= 1"
          class="flex items-center gap-1 px-3 py-1.5 text-sm font-medium text-neutral-300 bg-neutral-800 hover:bg-neutral-700 disabled:opacity-40 disabled:cursor-not-allowed rounded-lg transition-colors"
        >
          <ChevronLeft class="w-4 h-4" />
          Prev
        </button>
        <button
          @click="nextPage"
          :disabled="page >= totalPages"
          class="flex items-center gap-1 px-3 py-1.5 text-sm font-medium text-neutral-300 bg-neutral-800 hover:bg-neutral-700 disabled:opacity-40 disabled:cursor-not-allowed rounded-lg transition-colors"
        >
          Next
          <ChevronRight class="w-4 h-4" />
        </button>
      </div>
    </div>
  </div>
</template>
