<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useApi } from '@/composables/useApi'
import { Key, Search, Download, Plus, X, ChevronLeft, ChevronRight } from 'lucide-vue-next'

const api = useApi()

interface License {
  id: string
  license_key: string
  owner_email: string
  server_name: string
  status: 'active' | 'suspended' | 'expired' | 'revoked'
  created_at: string
  expires_at: string
}

interface LicenseDetail {
  id: string
  license_key: string
  owner_email: string
  server_name: string
  status: string
  created_at: string
  expires_at: string
  team_count: number
  wipe_count: number
  server_connection: {
    connection_type: string
    server_ip: string
    game_port: number
    last_heartbeat: string
    status: string
  } | null
}

const licenses = ref<License[]>([])
const isLoading = ref(false)
const searchQuery = ref('')
const statusFilter = ref('all')
const page = ref(1)
const perPage = 25
const total = ref(0)

const selectedLicenseId = ref<string | null>(null)
const selectedDetail = ref<LicenseDetail | null>(null)
const isDetailLoading = ref(false)

const showGenerateForm = ref(false)
const generateEmail = ref('')
const isGenerating = ref(false)

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

const statusOptions = [
  { value: 'all', label: 'All' },
  { value: 'active', label: 'Active' },
  { value: 'suspended', label: 'Suspended' },
  { value: 'expired', label: 'Expired' },
  { value: 'revoked', label: 'Revoked' },
]

const statusBadgeClass: Record<string, string> = {
  active: 'bg-green-500/10 text-green-400',
  suspended: 'bg-yellow-500/10 text-yellow-400',
  expired: 'bg-neutral-700/50 text-neutral-400',
  revoked: 'bg-red-500/10 text-red-400',
}

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

async function fetchLicenses() {
  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())
    if (statusFilter.value !== 'all') params.set('status', statusFilter.value)

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

async function selectLicense(id: string) {
  if (selectedLicenseId.value === id) {
    selectedLicenseId.value = null
    selectedDetail.value = null
    return
  }
  selectedLicenseId.value = id
  isDetailLoading.value = true
  try {
    selectedDetail.value = await api.get<LicenseDetail>(`/admin/licenses/${id}`)
  } catch {
    selectedDetail.value = null
  } finally {
    isDetailLoading.value = false
  }
}

async function generateLicense() {
  if (!generateEmail.value.trim()) return
  isGenerating.value = true
  try {
    await api.post('/admin/licenses', { email: generateEmail.value.trim() })
    generateEmail.value = ''
    showGenerateForm.value = false
    await fetchLicenses()
  } catch {
    // Handle error
  } finally {
    isGenerating.value = false
  }
}

function exportCsv() {
  if (!licenses.value.length) return
  const headers = ['License Key', 'Owner Email', 'Server Name', 'Status', 'Created', 'Expires']
  const rows = licenses.value.map(l => [
    l.license_key,
    l.owner_email,
    l.server_name,
    l.status,
    formatDate(l.created_at),
    formatDate(l.expires_at),
  ])
  const csv = [headers, ...rows].map(r => r.map(c => `"${c}"`).join(',')).join('\n')
  const blob = new Blob([csv], { type: 'text/csv' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `licenses-export-${new Date().toISOString().slice(0, 10)}.csv`
  a.click()
  URL.revokeObjectURL(url)
}

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

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

// Reset to page 1 when filters change
watch([searchQuery, statusFilter], () => {
  page.value = 1
})

// Refetch when page, search, or status changes
watch([page, searchQuery, statusFilter], () => {
  fetchLicenses()
})

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

<template>
  <div class="p-6 space-y-6 bg-neutral-950 min-h-screen">
    <!-- Header -->
    <div class="flex items-center justify-between">
      <div class="flex items-center gap-3">
        <Key class="w-5 h-5 text-oxide-500" />
        <div>
          <h1 class="text-2xl font-bold text-neutral-100">License Management</h1>
          <p class="text-sm text-neutral-400 mt-0.5">{{ total }} licenses total</p>
        </div>
      </div>
      <div class="flex items-center gap-3">
        <button
          @click="exportCsv"
          class="flex items-center gap-2 px-4 py-2 text-sm font-medium text-neutral-300 bg-neutral-800 hover:bg-neutral-700 rounded-lg transition-colors"
        >
          <Download class="w-4 h-4" />
          Export CSV
        </button>
        <button
          @click="showGenerateForm = !showGenerateForm"
          class="flex items-center gap-2 px-4 py-2 text-sm font-medium text-white bg-oxide-600 hover:bg-oxide-700 rounded-lg transition-colors"
        >
          <Plus class="w-4 h-4" />
          Generate License
        </button>
      </div>
    </div>

    <!-- Generate License Form -->
    <div
      v-if="showGenerateForm"
      class="bg-neutral-900 border border-oxide-500/30 rounded-lg p-4"
    >
      <div class="flex items-center justify-between mb-3">
        <h3 class="text-sm font-semibold text-neutral-200">Generate New License</h3>
        <button @click="showGenerateForm = false" class="text-neutral-500 hover:text-neutral-300">
          <X class="w-4 h-4" />
        </button>
      </div>
      <div class="flex items-center gap-3">
        <input
          v-model="generateEmail"
          type="email"
          placeholder="Owner email address..."
          class="flex-1 px-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"
          @keydown.enter="generateLicense"
        />
        <button
          @click="generateLicense"
          :disabled="isGenerating || !generateEmail.trim()"
          class="px-4 py-2 text-sm font-medium text-white bg-oxide-600 hover:bg-oxide-700 disabled:opacity-50 disabled:cursor-not-allowed rounded-lg transition-colors"
        >
          {{ isGenerating ? 'Generating...' : 'Generate' }}
        </button>
      </div>
    </div>

    <!-- Filters -->
    <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 key, email, or server name..."
          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>
      <select
        v-model="statusFilter"
        class="px-3 py-2 bg-neutral-800 border border-neutral-700 rounded-lg text-sm text-neutral-100 focus:outline-none focus:ring-2 focus:ring-oxide-500/50 focus:border-oxide-500 transition-colors"
      >
        <option v-for="opt in statusOptions" :key="opt.value" :value="opt.value">
          {{ opt.label }}
        </option>
      </select>
    </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">License Key</th>
            <th class="px-4 py-3 text-xs font-medium text-neutral-500 uppercase tracking-wider">Owner Email</th>
            <th class="px-4 py-3 text-xs font-medium text-neutral-500 uppercase tracking-wider">Server Name</th>
            <th class="px-4 py-3 text-xs font-medium text-neutral-500 uppercase tracking-wider">Status</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">Expires</th>
          </tr>
        </thead>
        <tbody class="divide-y divide-neutral-800">
          <tr v-if="licenses.length === 0 && !isLoading">
            <td colspan="6" class="px-4 py-12 text-center text-neutral-500 text-sm">
              <template v-if="searchQuery || statusFilter !== 'all'">No licenses matching your filters.</template>
              <template v-else>No licenses found.</template>
            </td>
          </tr>
          <tr v-if="isLoading">
            <td colspan="6" class="px-4 py-12 text-center text-neutral-500 text-sm">Loading licenses...</td>
          </tr>
          <tr
            v-for="license in licenses"
            :key="license.id"
            @click="selectLicense(license.id)"
            class="hover:bg-neutral-800/50 transition-colors cursor-pointer"
            :class="{ 'bg-neutral-800/30': selectedLicenseId === license.id }"
          >
            <td class="px-4 py-3 text-sm text-neutral-100 font-mono">{{ license.license_key }}</td>
            <td class="px-4 py-3 text-sm text-neutral-400">{{ license.owner_email }}</td>
            <td class="px-4 py-3 text-sm text-neutral-400">{{ license.server_name }}</td>
            <td class="px-4 py-3">
              <span
                class="inline-flex text-xs font-medium px-2 py-0.5 rounded-full capitalize"
                :class="statusBadgeClass[license.status] || 'bg-neutral-700/50 text-neutral-400'"
              >
                {{ license.status }}
              </span>
            </td>
            <td class="px-4 py-3 text-sm text-neutral-400">{{ formatDate(license.created_at) }}</td>
            <td class="px-4 py-3 text-sm text-neutral-400">{{ formatDate(license.expires_at) }}</td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- Detail Panel -->
    <div
      v-if="selectedLicenseId"
      class="bg-neutral-900 border border-neutral-800 rounded-lg p-5"
    >
      <div v-if="isDetailLoading" class="space-y-3">
        <div class="h-5 w-40 bg-neutral-800 rounded animate-pulse" />
        <div class="h-4 w-64 bg-neutral-800 rounded animate-pulse" />
        <div class="h-4 w-48 bg-neutral-800 rounded animate-pulse" />
      </div>
      <div v-else-if="selectedDetail">
        <div class="flex items-center justify-between mb-4">
          <h3 class="text-lg font-semibold text-neutral-100">License Details</h3>
          <button @click="selectedLicenseId = null; selectedDetail = null" class="text-neutral-500 hover:text-neutral-300">
            <X class="w-4 h-4" />
          </button>
        </div>
        <div class="grid grid-cols-2 lg:grid-cols-4 gap-4 text-sm">
          <div>
            <span class="text-neutral-500">License Key</span>
            <p class="text-neutral-200 mt-0.5 font-mono text-xs">{{ selectedDetail.license_key }}</p>
          </div>
          <div>
            <span class="text-neutral-500">Owner</span>
            <p class="text-neutral-200 mt-0.5">{{ selectedDetail.owner_email }}</p>
          </div>
          <div>
            <span class="text-neutral-500">Team Members</span>
            <p class="text-neutral-200 mt-0.5">{{ selectedDetail.team_count }}</p>
          </div>
          <div>
            <span class="text-neutral-500">Wipe Count</span>
            <p class="text-neutral-200 mt-0.5">{{ selectedDetail.wipe_count }}</p>
          </div>
        </div>
        <div v-if="selectedDetail.server_connection" class="mt-4 pt-4 border-t border-neutral-800">
          <h4 class="text-sm font-medium text-neutral-300 mb-3">Server Connection</h4>
          <div class="grid grid-cols-2 lg:grid-cols-4 gap-4 text-sm">
            <div>
              <span class="text-neutral-500">Connection Type</span>
              <p class="text-neutral-200 mt-0.5 capitalize">{{ selectedDetail.server_connection.connection_type }}</p>
            </div>
            <div>
              <span class="text-neutral-500">Server IP</span>
              <p class="text-neutral-200 mt-0.5 font-mono">{{ selectedDetail.server_connection.server_ip }}</p>
            </div>
            <div>
              <span class="text-neutral-500">Game Port</span>
              <p class="text-neutral-200 mt-0.5 font-mono">{{ selectedDetail.server_connection.game_port }}</p>
            </div>
            <div>
              <span class="text-neutral-500">Status</span>
              <p class="text-neutral-200 mt-0.5 capitalize">{{ selectedDetail.server_connection.status }}</p>
            </div>
          </div>
        </div>
      </div>
    </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>
