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

interface ServiceUser {
  id: number
  name: string
  email: string
}

interface ServicePlan {
  id: number
  name: string
  service_type: string
  price: string
  billing_cycle: string
}

interface ServiceItem {
  id: number
  user_id: number
  service_type: string
  platform: string | null
  platform_service_id: string | null
  status: string
  hostname: string | null
  domain: string | null
  ipv4_address: string | null
  created_at: string
  deleted_at: string | null
  user: ServiceUser | null
  plan: ServicePlan | null
}

interface Filters {
  search: string
  service_type: string
  status: string
  show_archived: boolean
}

interface Props {
  services: PaginatedResponse<ServiceItem>
  filters: Filters
}

defineOptions({ layout: AdminLayout })

const props = defineProps<Props>()

const search = ref<string>(props.filters.search)
const serviceType = ref<string>(props.filters.service_type)
const status = ref<string>(props.filters.status)
const showArchived = ref<boolean>(props.filters.show_archived)

const deleteDialog = ref<boolean>(false)
const serviceToDelete = ref<ServiceItem | null>(null)
const deleteForm = useForm({})

const serviceTypeOptions = [
  { title: 'All Types', value: '' },
  { title: 'VPS', value: 'vps' },
  { title: 'Dedicated', value: 'dedicated' },
  { title: 'Web Hosting', value: 'web_hosting' },
  { title: 'Game Hosting', value: 'game' },
]

const statusOptions = [
  { title: 'All Statuses', value: '' },
  { title: 'Active', value: 'active' },
  { title: 'Suspended', value: 'suspended' },
  { title: 'Terminated', value: 'terminated' },
  { title: 'Pending', value: 'pending' },
  { title: 'Failed', value: 'failed' },
]

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

function applyFilters(): void {
  router.get('/services', {
    search: search.value || undefined,
    service_type: serviceType.value || undefined,
    status: status.value || undefined,
    show_archived: showArchived.value || undefined,
  }, {
    preserveState: true,
    preserveScroll: true,
  })
}

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

watch([serviceType, status, showArchived], () => {
  applyFilters()
})

function openDeleteDialog(service: ServiceItem): void {
  serviceToDelete.value = service
  deleteDialog.value = true
}

function confirmDelete(): void {
  if (!serviceToDelete.value) return
  deleteForm.delete(`/services/${serviceToDelete.value.id}`, {
    preserveScroll: true,
    onSuccess: () => {
      deleteDialog.value = false
      serviceToDelete.value = null
    },
  })
}

function resolveServiceStatusColor(statusVal: string): StatusColor {
  const map: Record<string, StatusColor> = {
    active: 'success',
    suspended: 'warning',
    terminated: 'error',
    pending: 'info',
    failed: 'error',
  }
  return map[statusVal] ?? 'secondary'
}

function resolveServiceTypeColor(type: string): string {
  const map: Record<string, string> = {
    vps: 'primary',
    dedicated: 'info',
    web_hosting: 'success',
    game: 'warning',
  }
  return map[type] ?? 'secondary'
}

function formatServiceType(type: string): string {
  const map: Record<string, string> = {
    vps: 'VPS',
    dedicated: 'Dedicated',
    web_hosting: 'Web Hosting',
    game: 'Game Hosting',
  }
  return map[type] ?? type
}

function formatDate(dateStr: string): string {
  const date = new Date(dateStr)
  return date.toLocaleDateString('en-US', { month: 'short', day: '2-digit', year: 'numeric' })
}
</script>

<template>
  <div>
    <div class="d-flex align-center justify-space-between mb-6">
      <div>
        <div class="text-h4 font-weight-bold">
          Services
        </div>
        <div class="text-body-2 text-medium-emphasis">
          Manage all customer services
        </div>
      </div>
    </div>

    <!-- Filters -->
    <VCard class="mb-6">
      <VCardText>
        <VRow>
          <VCol cols="12" md="5">
            <VTextField
              v-model="search"
              prepend-inner-icon="tabler-search"
              placeholder="Search by customer name or email..."
              density="compact"
              clearable
              hide-details
              @click:clear="search = ''"
            />
          </VCol>
          <VCol cols="12" sm="6" md="2">
            <VSelect
              v-model="serviceType"
              :items="serviceTypeOptions"
              density="compact"
              hide-details
              label="Service Type"
            />
          </VCol>
          <VCol cols="12" sm="6" md="2">
            <VSelect
              v-model="status"
              :items="statusOptions"
              density="compact"
              hide-details
              label="Status"
            />
          </VCol>
          <VCol cols="12" sm="6" md="3" class="d-flex align-center">
            <VSwitch
              v-model="showArchived"
              label="Show archived"
              density="compact"
              hide-details
              color="primary"
            />
          </VCol>
        </VRow>
      </VCardText>
    </VCard>

    <!-- Services Table -->
    <VCard>
      <VCardText v-if="services.data.length === 0" class="text-center py-12">
        <VIcon icon="tabler-server-off" size="48" color="disabled" class="mb-2" />
        <div class="text-medium-emphasis">
          No services found.
        </div>
      </VCardText>

      <VTable v-else density="comfortable" hover>
        <thead>
          <tr>
            <th>ID</th>
            <th>Customer</th>
            <th>Plan</th>
            <th>Type</th>
            <th>Status</th>
            <th>Platform ID</th>
            <th>Created</th>
            <th class="text-center">
              Actions
            </th>
          </tr>
        </thead>
        <tbody>
          <tr
            v-for="service in services.data"
            :key="service.id"
            :class="{ 'opacity-50': service.deleted_at }"
          >
            <td class="text-body-2 font-weight-medium">
              #{{ service.id }}
            </td>
            <td>
              <div class="d-flex flex-column">
                <span class="text-body-2 font-weight-medium">{{ service.user?.name ?? 'Unknown' }}</span>
                <span class="text-caption text-medium-emphasis">{{ service.user?.email ?? '' }}</span>
              </div>
            </td>
            <td class="text-body-2">
              {{ service.plan?.name ?? 'N/A' }}
            </td>
            <td>
              <VChip
                :color="resolveServiceTypeColor(service.service_type)"
                size="small"
                variant="tonal"
              >
                {{ formatServiceType(service.service_type) }}
              </VChip>
            </td>
            <td>
              <VChip
                v-if="service.deleted_at"
                color="secondary"
                size="small"
                variant="outlined"
              >
                Archived
              </VChip>
              <VChip
                v-else
                :color="resolveServiceStatusColor(service.status)"
                size="small"
                class="text-capitalize"
              >
                {{ service.status }}
              </VChip>
            </td>
            <td class="text-body-2 text-medium-emphasis">
              {{ service.platform_service_id ?? '---' }}
            </td>
            <td class="text-body-2">
              {{ formatDate(service.created_at) }}
            </td>
            <td class="text-center">
              <Link :href="`/services/${service.id}`">
                <VBtn variant="text" size="small" color="primary">
                  <VIcon icon="tabler-eye" size="18" />
                </VBtn>
              </Link>
              <VBtn
                v-if="!service.deleted_at"
                variant="text"
                size="small"
                color="error"
                @click="openDeleteDialog(service)"
              >
                <VIcon icon="tabler-archive" size="18" />
              </VBtn>
            </td>
          </tr>
        </tbody>
      </VTable>

      <!-- Pagination -->
      <VCardText v-if="services.last_page > 1" class="d-flex align-center justify-center pt-2">
        <VPagination
          :model-value="services.data.length > 0 ? Math.ceil((services.from ?? 1) / 15) : 1"
          :length="services.last_page"
          :total-visible="7"
          @update:model-value="(page: number) => router.get('/services', { ...props.filters, page }, { preserveState: true, preserveScroll: true })"
        />
      </VCardText>

      <VCardText v-if="services.total > 0" class="text-center text-caption text-medium-emphasis">
        Showing {{ services.from }} to {{ services.to }} of {{ services.total }} services
      </VCardText>
    </VCard>

    <!-- Delete Confirmation Dialog -->
    <VDialog v-model="deleteDialog" max-width="500" persistent>
      <VCard>
        <VCardTitle class="text-h5 pa-5">
          Archive Service
        </VCardTitle>
        <VCardText class="px-5 pb-2">
          Are you sure you want to archive service #{{ serviceToDelete?.id }}? The service will be hidden from the default list but can be restored later.
        </VCardText>
        <VCardActions class="pa-5">
          <VSpacer />
          <VBtn variant="text" :disabled="deleteForm.processing" @click="deleteDialog = false">
            Cancel
          </VBtn>
          <VBtn
            color="error"
            variant="flat"
            :loading="deleteForm.processing"
            @click="confirmDelete"
          >
            Archive
          </VBtn>
        </VCardActions>
      </VCard>
    </VDialog>
  </div>
</template>
