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

interface ConfigGroupListItem extends PlanConfigGroup {
  options_count: number
  plans_count: number
}

interface Filters {
  mode: string
  search: string
}

interface Props {
  configGroups: ConfigGroupListItem[]
  filters: Filters
}

defineOptions({ layout: AdminLayout })

const props = defineProps<Props>()

const search = ref<string>(props.filters.search)
const activeTab = ref<string>(props.filters.mode)

const modeTabs: { title: string; value: string }[] = [
  { title: 'All', value: 'all' },
  { title: 'Preset', value: 'preset' },
  { title: 'Build Your Own', value: 'build_your_own' },
]

function resolveModeColor(mode: string): StatusColor {
  return mode === 'preset' ? 'info' : 'primary'
}

function resolveModeLabel(mode: string): string {
  return mode === 'preset' ? 'Preset' : 'Build Your Own'
}

function resolveServiceTypeLabel(type: string | null): string {
  if (!type) return '-'
  const map: Record<string, string> = {
    vps: 'VPS',
    dedicated: 'Dedicated',
    hosting: 'Hosting',
    mysql: 'MySQL',
    game: 'Game Server',
    backups: 'Backups',
  }
  return map[type] ?? type
}

const tableHeaders = [
  { title: 'Name', key: 'name', sortable: true },
  { title: 'Mode', key: 'mode', sortable: true },
  { title: 'Service Type', key: 'service_type', sortable: true },
  { title: 'Plans', key: 'plans_count', sortable: true, align: 'center' as const },
  { title: 'Options', key: 'options_count', sortable: true, align: 'center' as const },
  { title: 'Active', key: 'is_active', sortable: true, align: 'center' as const },
  { title: 'Actions', key: 'actions', sortable: false, align: 'center' as const },
]

let searchTimeout: ReturnType<typeof setTimeout> | null = null

function applyFilters(): void {
  router.get('/config-groups', {
    mode: activeTab.value,
    search: search.value || undefined,
  }, {
    preserveState: true,
    replace: true,
  })
}

watch(activeTab, () => {
  applyFilters()
})

watch(search, () => {
  if (searchTimeout) {
    clearTimeout(searchTimeout)
  }
  searchTimeout = setTimeout(() => {
    applyFilters()
  }, 300)
})

function deleteGroup(group: ConfigGroupListItem): void {
  if (confirm(`Are you sure you want to delete "${group.name}"?`)) {
    router.delete(`/config-groups/${group.id}`, {
      preserveScroll: true,
    })
  }
}
</script>

<template>
  <div>
    <!-- Header -->
    <div class="d-flex align-center justify-space-between mb-6">
      <div>
        <div class="text-h4 font-weight-bold">
          Config Options
        </div>
        <div class="text-body-2 text-medium-emphasis">
          Manage configurable option groups for plans
        </div>
      </div>
      <Link href="/config-groups/create">
        <VBtn color="primary" prepend-icon="tabler-plus">
          Create Config Group
        </VBtn>
      </Link>
    </div>

    <!-- Filters -->
    <VCard class="mb-6">
      <VCardText>
        <VRow align="center">
          <VCol cols="12" md="8">
            <VTabs
              v-model="activeTab"
              density="comfortable"
            >
              <VTab
                v-for="tab in modeTabs"
                :key="tab.value"
                :value="tab.value"
              >
                {{ tab.title }}
              </VTab>
            </VTabs>
          </VCol>
          <VCol cols="12" md="4">
            <VTextField
              v-model="search"
              placeholder="Search config groups..."
              prepend-inner-icon="tabler-search"
              variant="outlined"
              density="compact"
              clearable
              hide-details
            />
          </VCol>
        </VRow>
      </VCardText>
    </VCard>

    <!-- Table -->
    <VCard>
      <VDataTable
        :headers="tableHeaders"
        :items="configGroups"
        :items-per-page="25"
        hover
        class="text-no-wrap"
      >
        <!-- Name -->
        <template #item.name="{ item }">
          <div class="d-flex flex-column py-2">
            <span class="text-body-1 font-weight-medium">{{ item.name }}</span>
            <span
              v-if="item.description"
              class="text-caption text-medium-emphasis text-truncate"
              style="max-width: 300px;"
            >
              {{ item.description }}
            </span>
          </div>
        </template>

        <!-- Mode -->
        <template #item.mode="{ item }">
          <VChip
            :color="resolveModeColor(item.mode)"
            size="small"
            variant="tonal"
          >
            {{ resolveModeLabel(item.mode) }}
          </VChip>
        </template>

        <!-- Service Type -->
        <template #item.service_type="{ item }">
          {{ resolveServiceTypeLabel(item.service_type) }}
        </template>

        <!-- Plans count -->
        <template #item.plans_count="{ item }">
          <span class="font-weight-medium">{{ item.plans_count }}</span>
        </template>

        <!-- Options count -->
        <template #item.options_count="{ item }">
          <span class="font-weight-medium">{{ item.options_count }}</span>
        </template>

        <!-- Active -->
        <template #item.is_active="{ item }">
          <VChip
            :color="item.is_active ? 'success' : 'error'"
            size="small"
          >
            {{ item.is_active ? 'Active' : 'Inactive' }}
          </VChip>
        </template>

        <!-- Actions -->
        <template #item.actions="{ item }">
          <VMenu>
            <template #activator="{ props: menuProps }">
              <VBtn
                icon="tabler-dots-vertical"
                variant="text"
                size="small"
                v-bind="menuProps"
              />
            </template>
            <VList density="compact">
              <Link :href="`/config-groups/${item.id}/edit`" class="text-decoration-none">
                <VListItem prepend-icon="tabler-edit">
                  <VListItemTitle>Edit</VListItemTitle>
                </VListItem>
              </Link>
              <VListItem
                prepend-icon="tabler-trash"
                @click="deleteGroup(item)"
              >
                <VListItemTitle>Delete</VListItemTitle>
              </VListItem>
            </VList>
          </VMenu>
        </template>

        <!-- No data -->
        <template #no-data>
          <div class="text-center py-8">
            <VIcon icon="tabler-adjustments" size="48" color="disabled" class="mb-2" />
            <div class="text-medium-emphasis">
              No config groups found.
            </div>
          </div>
        </template>
      </VDataTable>
    </VCard>
  </div>
</template>
