<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 Select from '@/components/ds/forms/Select.vue'
import EmptyState from '@/components/ds/feedback/EmptyState.vue'

const api = useApi()

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

interface LicenseDetail {
  id: string
  license_key: string
  owner_email: string
  server_name: string | null
  status: string
  created_at: string
  expires_at: string | null
  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 statusTone: Record<string, 'online' | 'warn' | 'neutral' | 'offline'> = {
  active: 'online',
  suspended: 'warn',
  expired: 'neutral',
  revoked: 'offline',
}

function formatDate(iso: string | null | undefined): string {
  if (!iso) return '—'
  const d = new Date(iso)
  if (isNaN(d.getTime()) || d.getTime() === 0) return '—'
  return d.toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
  })
}

async function fetchLicenses() {
  isLoading.value = true
  try {
    const params = new URLSearchParams({
      page: page.value.toString(),
      limit: 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="pal">
    <!-- Page head -->
    <div class="pal__head">
      <div class="pal__head-id">
        <div class="pal__chip">
          <Icon name="key" :size="20" :stroke-width="2" />
        </div>
        <div>
          <div class="t-eyebrow">Platform admin</div>
          <h1 class="pal__title">License management</h1>
        </div>
      </div>
      <div class="pal__head-actions">
        <Button variant="secondary" icon="download" @click="exportCsv">Export CSV</Button>
        <Button icon="plus" @click="showGenerateForm = !showGenerateForm">Generate license</Button>
      </div>
    </div>

    <!-- Generate license form -->
    <Panel v-if="showGenerateForm" title="Generate new license">
      <template #actions>
        <IconButton icon="x" label="Close" @click="showGenerateForm = false" />
      </template>
      <div class="pal__gen-form">
        <Input
          v-model="generateEmail"
          type="email"
          placeholder="Owner email address"
          icon="mail"
          style="flex: 1"
          @keydown.enter="generateLicense"
        />
        <Button
          icon="key"
          :loading="isGenerating"
          :disabled="isGenerating || !generateEmail.trim()"
          @click="generateLicense"
        >{{ isGenerating ? 'Generating...' : 'Generate' }}</Button>
      </div>
    </Panel>

    <!-- Filters -->
    <div class="pal__filters">
      <Input
        v-model="searchQuery"
        placeholder="Search by key, email, or server name"
        icon="search"
        style="flex: 1; max-width: 360px"
      />
      <Select
        v-model="statusFilter"
        :options="statusOptions"
      />
    </div>

    <!-- Table -->
    <Panel :flush-body="true" :subtitle="total + ' licenses total'">
      <table class="pal__table">
        <thead>
          <tr class="pal__thead-row">
            <th class="pal__th">License key</th>
            <th class="pal__th">Owner email</th>
            <th class="pal__th">Server name</th>
            <th class="pal__th">Status</th>
            <th class="pal__th">Created</th>
            <th class="pal__th">Expires</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="isLoading">
            <td colspan="6" class="pal__td-empty">Loading licenses...</td>
          </tr>
          <tr v-else-if="licenses.length === 0">
            <td colspan="6" class="pal__td-es">
              <EmptyState
                icon="key"
                :title="(searchQuery || statusFilter !== 'all') ? 'No matching licenses' : 'No licenses found'"
                :description="(searchQuery || statusFilter !== 'all') ? 'Try adjusting your search or filter.' : 'Generate a license to get started.'"
              />
            </td>
          </tr>
          <tr
            v-for="license in licenses"
            :key="license.id"
            class="pal__tr"
            :class="{ 'pal__tr--selected': selectedLicenseId === license.id }"
            @click="selectLicense(license.id)"
          >
            <td class="pal__td pal__td--mono">{{ license.license_key }}</td>
            <td class="pal__td pal__td--secondary">{{ license.owner_email }}</td>
            <td class="pal__td pal__td--secondary">{{ license.server_name ?? '—' }}</td>
            <td class="pal__td">
              <Badge :tone="statusTone[license.status] ?? 'neutral'">{{ license.status }}</Badge>
            </td>
            <td class="pal__td pal__td--secondary">{{ formatDate(license.created_at) }}</td>
            <td class="pal__td pal__td--secondary">{{ formatDate(license.expires_at) }}</td>
          </tr>
        </tbody>
      </table>
    </Panel>

    <!-- Detail panel -->
    <Panel v-if="selectedLicenseId" title="License details">
      <template #actions>
        <IconButton icon="x" label="Close" @click="selectedLicenseId = null; selectedDetail = null" />
      </template>
      <div v-if="isDetailLoading" class="pal__detail-skeleton">
        <div class="pal__skel" />
        <div class="pal__skel pal__skel--wide" />
        <div class="pal__skel" />
      </div>
      <div v-else-if="selectedDetail">
        <div class="pal__detail-grid">
          <div class="pal__field">
            <div class="pal__field-label">License key</div>
            <div class="pal__field-val pal__field-val--mono">{{ selectedDetail.license_key }}</div>
          </div>
          <div class="pal__field">
            <div class="pal__field-label">Owner</div>
            <div class="pal__field-val">{{ selectedDetail.owner_email }}</div>
          </div>
          <div class="pal__field">
            <div class="pal__field-label">Team members</div>
            <div class="pal__field-val pal__field-val--mono">{{ selectedDetail.team_count }}</div>
          </div>
          <div class="pal__field">
            <div class="pal__field-label">Wipe count</div>
            <div class="pal__field-val pal__field-val--mono">{{ selectedDetail.wipe_count }}</div>
          </div>
        </div>
        <div v-if="selectedDetail.server_connection" class="pal__conn">
          <div class="pal__conn-head">Server connection</div>
          <div class="pal__detail-grid">
            <div class="pal__field">
              <div class="pal__field-label">Connection type</div>
              <div class="pal__field-val pal__field-val--mono">{{ selectedDetail.server_connection.connection_type }}</div>
            </div>
            <div class="pal__field">
              <div class="pal__field-label">Server IP</div>
              <div class="pal__field-val pal__field-val--mono">{{ selectedDetail.server_connection.server_ip }}</div>
            </div>
            <div class="pal__field">
              <div class="pal__field-label">Game port</div>
              <div class="pal__field-val pal__field-val--mono">{{ selectedDetail.server_connection.game_port }}</div>
            </div>
            <div class="pal__field">
              <div class="pal__field-label">Status</div>
              <div class="pal__field-val">{{ selectedDetail.server_connection.status }}</div>
            </div>
          </div>
        </div>
      </div>
    </Panel>

    <!-- Pagination -->
    <div class="pal__pager">
      <span class="pal__pager-info">Page {{ page }} of {{ totalPages }}</span>
      <div class="pal__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>
.pal { max-width: 1200px; margin: 0 auto; display: flex; flex-direction: column; gap: 16px; }

/* Page head */
.pal__head { display: flex; align-items: flex-end; justify-content: space-between; flex-wrap: wrap; gap: 12px; row-gap: 10px; }
.pal__head-id { display: flex; align-items: center; gap: 12px; }
.pal__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);
}
.pal__title {
  font-size: var(--text-2xl); font-weight: 700; letter-spacing: -0.02em;
  color: var(--text-primary); margin-top: 3px;
}
.pal__head-actions { display: flex; align-items: center; gap: 8px; }

/* Generate form */
.pal__gen-form { display: flex; align-items: flex-end; gap: 10px; }

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

/* Table */
.pal__table { width: 100%; border-collapse: collapse; }
.pal__thead-row { border-bottom: 1px solid var(--border-subtle); }
.pal__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;
}
.pal__tr { border-bottom: 1px solid var(--border-subtle); cursor: pointer; transition: var(--transition-colors); }
.pal__tr:last-child { border-bottom: 0; }
.pal__tr:hover { background: var(--surface-hover); }
.pal__tr--selected { background: var(--accent-soft); }
.pal__td { padding: 11px 16px; font-size: var(--text-sm); color: var(--text-primary); }
.pal__td--secondary { color: var(--text-secondary); }
.pal__td--mono { font-family: var(--font-mono); font-variant-numeric: tabular-nums; font-size: var(--text-xs); }
.pal__td-empty { padding: 12px 16px; text-align: center; font-size: var(--text-sm); color: var(--text-tertiary); }
.pal__td-es { padding: 0; }

/* Detail panel */
.pal__detail-skeleton { display: flex; flex-direction: column; gap: 10px; }
.pal__skel { height: 16px; width: 160px; background: var(--surface-raised-2); border-radius: var(--radius-sm); animation: pal-pulse 1.4s ease-in-out infinite; }
.pal__skel--wide { width: 260px; }
@keyframes pal-pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.4; } }

.pal__detail-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 20px; }
.pal__field-label { font-size: var(--text-xs); color: var(--text-tertiary); margin-bottom: 4px; }
.pal__field-val { font-size: var(--text-sm); font-weight: 500; color: var(--text-primary); }
.pal__field-val--mono { font-family: var(--font-mono); font-variant-numeric: tabular-nums; font-size: var(--text-xs); }

.pal__conn { margin-top: 20px; padding-top: 20px; border-top: 1px solid var(--border-subtle); }
.pal__conn-head { font-size: var(--text-xs); font-weight: 600; color: var(--text-tertiary); text-transform: uppercase; letter-spacing: var(--tracking-wider); margin-bottom: 14px; }

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

@media (max-width: 900px) {
  .pal__detail-grid { grid-template-columns: repeat(2, 1fr); }
}
</style>
