<script lang="ts" setup>
import { ref, computed } from 'vue'
import { Link, useForm, usePage } from '@inertiajs/vue3'
import AccountLayout from '@/Layouts/AccountLayout.vue'
import {
  resolveServiceStatusColor,
  resolveServiceTypeColor,
  resolvePlatformUrl,
  formatPrice,
} from '@/utils/resolvers'
import type { Service } from '@/types'

interface Props {
  service: Service
}

defineOptions({ layout: AccountLayout })

const props = defineProps<Props>()

const page = usePage()
const newPassword = computed(() => (page.props as Record<string, unknown>).flash as Record<string, string> | undefined)
const showPasswordDialog = ref(!!newPassword.value?.new_password)

// Forms for VPS operations
const powerForm = useForm({})
const rebuildDialog = ref(false)
const rebuildForm = useForm({
  template_id: null as number | null,
})

const templates = ref([
  { id: 1, name: 'Ubuntu 22.04 LTS', icon: 'tabler-brand-ubuntu' },
  { id: 2, name: 'Debian 12', icon: 'tabler-brand-debian' },
  { id: 3, name: 'CentOS 9', icon: 'tabler-brand-redhat' },
  { id: 4, name: 'Windows Server 2022', icon: 'tabler-brand-windows' },
])

function formatDate(dateStr: string | null): string {
  if (!dateStr) return '--'
  return new Date(dateStr).toLocaleDateString()
}

function formatDateTime(dateStr: string | null): string {
  if (!dateStr) return '--'
  return new Date(dateStr).toLocaleString()
}

const panelBases = computed<Record<string, string>>(() => {
  return ((page.props as Record<string, unknown>).panels as Record<string, string>) ?? {}
})

const controlPanelUrl = computed<string | null>(() => {
  return resolvePlatformUrl(props.service.platform, props.service.platform_service_id, panelBases.value)
})

const isSuspended = computed<boolean>(() => props.service.status === 'suspended')
const isTerminated = computed<boolean>(() => props.service.status === 'terminated')
const isVps = computed<boolean>(() => props.service.service_type === 'vps')
const isDedicated = computed<boolean>(() => props.service.service_type === 'dedicated')
const isGame = computed<boolean>(() => props.service.service_type === 'game')
const isWebHosting = computed<boolean>(() => props.service.service_type === 'hosting')
const isActive = computed<boolean>(() => props.service.status === 'active')

const platformLabel = computed<string>(() => {
  const labels: Record<string, string> = {
    virtfusion: 'VirtFusion',
    synergycp: 'SynergyCP',
    enhance: 'Enhance',
    pterodactyl: 'Pterodactyl',
  }
  return labels[props.service.platform] ?? props.service.platform
})

const serviceTypeLabel = computed<string>(() => {
  const labels: Record<string, string> = {
    vps: 'VPS',
    dedicated: 'Dedicated Server',
    game: 'Game Server',
    hosting: 'Web Hosting',
  }
  return labels[props.service.service_type] ?? props.service.service_type
})

const serviceTypeIcon = computed<string>(() => {
  const icons: Record<string, string> = {
    vps: 'tabler-server',
    dedicated: 'tabler-server-2',
    game: 'tabler-device-gamepad-2',
    hosting: 'tabler-world-www',
  }
  return icons[props.service.service_type] ?? 'tabler-server'
})

const provisioningEntries = computed<Array<{ key: string; value: string }>>(() => {
  const info = props.service.provisioning_info
  if (!info || typeof info !== 'object') return []

  return Object.entries(info).map(([key, value]) => ({
    key: key.replace(/_/g, ' '),
    value: String(value),
  }))
})

const connectionString = computed<string | null>(() => {
  const info = props.service.provisioning_info
  if (!info) return null

  if (isGame.value) {
    const port = info.port ?? info.game_port
    if (props.service.ipv4_address && port) {
      return `${props.service.ipv4_address}:${port}`
    }
  }

  return null
})

// VPS Control Functions
function performPowerAction(action: 'boot' | 'shutdown' | 'restart' | 'poweroff') {
  powerForm.post(`/services/${props.service.id}/vps/${action}`, {
    preserveScroll: true,
  })
}

function resetPassword() {
  if (confirm('Are you sure you want to reset the root password? This will generate a new random password.')) {
    powerForm.post(`/services/${props.service.id}/vps/reset-password`, {
      preserveScroll: true,
      onSuccess: () => { showPasswordDialog.value = true },
    })
  }
}

function openVnc() {
  window.open(`/services/${props.service.id}/vps/vnc`, '_blank', 'width=1024,height=768')
}

function submitRebuild() {
  if (!rebuildForm.template_id) return

  if (confirm('WARNING: Rebuilding will erase all data on this VPS. This action cannot be undone. Are you sure?')) {
    rebuildForm.post(`/services/${props.service.id}/vps/rebuild`, {
      preserveScroll: true,
      onSuccess: () => {
        rebuildDialog.value = false
        rebuildForm.reset()
      },
    })
  }
}
</script>

<template>
  <div>
    <!-- Breadcrumb -->
    <div class="mb-6">
      <VBreadcrumbs
        :items="[
          { title: 'Services', to: '/services', disabled: false },
          { title: service.hostname || service.domain || `Service #${service.id}`, disabled: true },
        ]"
        class="pa-0"
      >
        <template #divider>
          <VIcon icon="tabler-chevron-right" size="16" />
        </template>
      </VBreadcrumbs>
    </div>

    <!-- Service Header -->
    <div class="service-header mb-8 pa-6" elevation="0">
      <div class="d-flex flex-wrap align-center justify-space-between gap-6">
        <div class="d-flex align-center gap-4">
          <VAvatar
            :color="resolveServiceTypeColor(service.service_type)"
            variant="flat"
            size="64"
            class="service-avatar"
          >
            <VIcon
              :icon="serviceTypeIcon"
              size="32"
              color="white"
            />
          </VAvatar>
          <div>
            <div class="d-flex flex-wrap align-center gap-3 mb-2">
              <h1 class="text-h3 font-weight-bold" style="font-family: 'DM Sans', sans-serif; letter-spacing: -0.02em;">
                {{ service.hostname || service.domain || `Service #${service.id}` }}
              </h1>
              <VChip
                :color="resolveServiceStatusColor(service.status)"
                size="default"
                class="text-capitalize status-indicator"
              >
                <VIcon
                  icon="tabler-circle-filled"
                  size="8"
                  start
                />
                {{ service.status }}
              </VChip>
              <VChip
                :color="resolveServiceTypeColor(service.service_type)"
                size="default"
                variant="tonal"
              >
                {{ serviceTypeLabel }}
              </VChip>
            </div>
            <div class="text-body-1 text-medium-emphasis">
              <VIcon icon="tabler-server-cog" size="18" class="me-1" />
              Managed by {{ platformLabel }}
              <span v-if="service.platform_service_id" class="ms-2">
                <VIcon icon="tabler-hash" size="16" />
                {{ service.platform_service_id }}
              </span>
            </div>
          </div>
        </div>
        <div class="d-flex flex-wrap gap-3">
          <Link
            v-if="isActive && service.plan"
            :href="`/services/${service.id}/upgrade`"
            class="text-decoration-none"
          >
            <VBtn
              color="primary"
              variant="tonal"
              size="large"
              class="text-none"
            >
              <VIcon icon="tabler-arrow-up" start />
              Upgrade
            </VBtn>
          </Link>
          <VBtn
            v-if="controlPanelUrl && !isTerminated"
            :href="controlPanelUrl"
            target="_blank"
            rel="noopener noreferrer"
            size="large"
            class="text-none"
          >
            <VIcon icon="tabler-external-link" start />
            Control Panel
          </VBtn>
        </div>
      </div>
    </div>

    <!-- Alerts -->
    <VAlert
      v-if="isSuspended"
      type="error"
      variant="tonal"
      class="mb-6"
      prominent
    >
      <VAlertTitle class="font-weight-bold">
        <VIcon icon="tabler-alert-octagon" start />
        Service Suspended
      </VAlertTitle>
      This service was suspended on {{ formatDateTime(service.suspended_at) }}.
      Please contact support or check your billing status to resolve this issue.
    </VAlert>

    <VAlert
      v-if="isTerminated"
      type="warning"
      variant="tonal"
      class="mb-6"
      prominent
    >
      <VAlertTitle class="font-weight-bold">
        <VIcon icon="tabler-trash" start />
        Service Terminated
      </VAlertTitle>
      This service was terminated on {{ formatDateTime(service.terminated_at) }}.
      Data may no longer be recoverable.
    </VAlert>

    <VRow>
      <!-- Main Content -->
      <VCol cols="12" :lg="isVps && isActive ? 8 : 12">
        <!-- VPS Control Panel (for VPS services only) -->
        <VCard
          v-if="isVps && isActive"
          class="mb-6 vps-control-panel"
          elevation="0"
        >
          <VCardTitle class="d-flex align-center gap-2 text-h5 font-weight-bold" style="font-family: 'DM Sans', sans-serif;">
            <VIcon icon="tabler-command" color="primary" />
            VPS Control Panel
          </VCardTitle>
          <VCardText>
            <!-- Power Controls -->
            <div class="mb-6">
              <div class="text-subtitle-2 text-medium-emphasis mb-4">
                POWER MANAGEMENT
              </div>
              <div class="d-flex flex-wrap gap-3">
                <VBtn
                  color="success"
                  variant="flat"
                  :loading="powerForm.processing"
                  @click="performPowerAction('boot')"
                  class="power-btn text-none"
                  size="large"
                >
                  <VIcon icon="tabler-player-play" start size="20" />
                  Boot
                </VBtn>
                <VBtn
                  color="warning"
                  variant="flat"
                  :loading="powerForm.processing"
                  @click="performPowerAction('restart')"
                  class="power-btn text-none"
                  size="large"
                >
                  <VIcon icon="tabler-refresh" start size="20" />
                  Restart
                </VBtn>
                <VBtn
                  color="error"
                  variant="flat"
                  :loading="powerForm.processing"
                  @click="performPowerAction('shutdown')"
                  class="power-btn text-none"
                  size="large"
                >
                  <VIcon icon="tabler-player-stop" start size="20" />
                  Shutdown
                </VBtn>
                <VBtn
                  color="error"
                  variant="outlined"
                  :loading="powerForm.processing"
                  @click="performPowerAction('poweroff')"
                  class="power-btn text-none"
                  size="large"
                >
                  <VIcon icon="tabler-power" start size="20" />
                  Force Power Off
                </VBtn>
              </div>
            </div>

            <VDivider class="my-6" />

            <!-- Quick Actions -->
            <div class="mb-6">
              <div class="text-subtitle-2 text-medium-emphasis mb-4">
                QUICK ACTIONS
              </div>
              <div class="d-flex flex-wrap gap-3">
                <VBtn
                  color="primary"
                  variant="tonal"
                  :loading="powerForm.processing"
                  @click="resetPassword"
                  class="text-none"
                >
                  <VIcon icon="tabler-key" start />
                  Reset Root Password
                </VBtn>
                <VBtn
                  color="primary"
                  variant="tonal"
                  @click="openVnc"
                  class="text-none"
                >
                  <VIcon icon="tabler-device-desktop" start />
                  Open VNC Console
                </VBtn>
                <VBtn
                  color="primary"
                  variant="tonal"
                  @click="rebuildDialog = true"
                  class="text-none"
                >
                  <VIcon icon="tabler-reload" start />
                  Rebuild VPS
                </VBtn>
              </div>
            </div>

            <!-- Server Info Quick View -->
            <VCard variant="tonal" color="primary" class="mt-6">
              <VCardText>
                <VRow>
                  <VCol cols="12" sm="6">
                    <div class="text-caption text-medium-emphasis mb-1">
                      IPv4 ADDRESS
                    </div>
                    <div class="text-body-1 font-weight-bold">
                      <code v-if="service.ipv4_address" class="server-info-code">{{ service.ipv4_address }}</code>
                      <span v-else>Not assigned</span>
                    </div>
                  </VCol>
                  <VCol cols="12" sm="6">
                    <div class="text-caption text-medium-emphasis mb-1">
                      HOSTNAME
                    </div>
                    <div class="text-body-1 font-weight-bold">
                      <code v-if="service.hostname" class="server-info-code">{{ service.hostname }}</code>
                      <span v-else>Not set</span>
                    </div>
                  </VCol>
                </VRow>
              </VCardText>
            </VCard>
          </VCardText>
        </VCard>

        <!-- Plan Details -->
        <VCard class="mb-6" elevation="0">
          <VCardTitle class="d-flex align-center gap-2">
            <VIcon icon="tabler-package" color="primary" />
            Plan Details
          </VCardTitle>
          <VCardText>
            <VRow>
              <VCol cols="12" sm="6" md="4">
                <div class="detail-item">
                  <div class="detail-label">Plan</div>
                  <div class="detail-value">{{ service.plan?.name || '--' }}</div>
                </div>
              </VCol>
              <VCol cols="12" sm="6" md="4">
                <div class="detail-item">
                  <div class="detail-label">Price</div>
                  <div class="detail-value">
                    {{ service.plan ? formatPrice(service.plan.price, service.plan.billing_cycle) : '--' }}
                  </div>
                </div>
              </VCol>
              <VCol cols="12" sm="6" md="4">
                <div class="detail-item">
                  <div class="detail-label">Billing Cycle</div>
                  <div class="detail-value text-capitalize">
                    {{ service.plan?.billing_cycle || '--' }}
                  </div>
                </div>
              </VCol>
              <VCol cols="12" sm="6" md="4">
                <div class="detail-item">
                  <div class="detail-label">Service Type</div>
                  <div class="detail-value">{{ serviceTypeLabel }}</div>
                </div>
              </VCol>
              <VCol cols="12" sm="6" md="4">
                <div class="detail-item">
                  <div class="detail-label">Platform</div>
                  <div class="detail-value">{{ platformLabel }}</div>
                </div>
              </VCol>
              <VCol cols="12" sm="6" md="4">
                <div class="detail-item">
                  <div class="detail-label">Auto Renew</div>
                  <div class="detail-value">
                    <VChip
                      :color="service.auto_renew ? 'success' : 'secondary'"
                      size="small"
                      variant="flat"
                    >
                      <VIcon
                        :icon="service.auto_renew ? 'tabler-check' : 'tabler-x'"
                        start
                        size="16"
                      />
                      {{ service.auto_renew ? 'Enabled' : 'Disabled' }}
                    </VChip>
                  </div>
                </div>
              </VCol>
            </VRow>

            <!-- Plan Features -->
            <div
              v-if="service.plan?.features && Object.keys(service.plan.features).length > 0"
              class="mt-6"
            >
              <div class="text-subtitle-2 text-medium-emphasis mb-3">
                PLAN FEATURES
              </div>
              <VRow>
                <VCol
                  v-for="(value, key) in service.plan.features"
                  :key="String(key)"
                  cols="12"
                  sm="6"
                  md="4"
                >
                  <div class="feature-item">
                    <VIcon icon="tabler-check" color="success" size="18" class="me-2" />
                    <span class="text-body-2">
                      <span class="font-weight-semibold text-capitalize">{{ String(key).replace(/_/g, ' ') }}:</span>
                      {{ value }}
                    </span>
                  </div>
                </VCol>
              </VRow>
            </div>
          </VCardText>
        </VCard>

        <!-- Service-Specific Details Cards -->
        <!-- VPS Details -->
        <VCard v-if="isVps" class="mb-6" elevation="0">
          <VCardTitle class="d-flex align-center gap-2">
            <VIcon icon="tabler-server" color="primary" />
            Server Information
          </VCardTitle>
          <VCardText>
            <VRow>
              <VCol cols="12" sm="6">
                <div class="detail-item">
                  <div class="detail-label">IPv4 Address</div>
                  <div class="detail-value">
                    <code v-if="service.ipv4_address">{{ service.ipv4_address }}</code>
                    <span v-else class="text-medium-emphasis">Not assigned</span>
                  </div>
                </div>
              </VCol>
              <VCol cols="12" sm="6">
                <div class="detail-item">
                  <div class="detail-label">Hostname</div>
                  <div class="detail-value">
                    <code v-if="service.hostname">{{ service.hostname }}</code>
                    <span v-else class="text-medium-emphasis">Not set</span>
                  </div>
                </div>
              </VCol>
              <VCol v-if="service.ipv6_address" cols="12">
                <div class="detail-item">
                  <div class="detail-label">IPv6 Address</div>
                  <div class="detail-value">
                    <code>{{ service.ipv6_address }}</code>
                  </div>
                </div>
              </VCol>
            </VRow>
          </VCardText>
        </VCard>

        <!-- Dedicated Server Details -->
        <VCard v-if="isDedicated" class="mb-6" elevation="0">
          <VCardTitle class="d-flex align-center gap-2">
            <VIcon icon="tabler-server-2" color="primary" />
            Dedicated Server Information
          </VCardTitle>
          <VCardText>
            <VRow>
              <VCol cols="12" sm="6">
                <div class="detail-item">
                  <div class="detail-label">Primary IPv4</div>
                  <div class="detail-value">
                    <code v-if="service.ipv4_address">{{ service.ipv4_address }}</code>
                    <span v-else class="text-medium-emphasis">Not assigned</span>
                  </div>
                </div>
              </VCol>
              <VCol cols="12" sm="6">
                <div class="detail-item">
                  <div class="detail-label">Hostname</div>
                  <div class="detail-value">
                    <code v-if="service.hostname">{{ service.hostname }}</code>
                    <span v-else class="text-medium-emphasis">Not set</span>
                  </div>
                </div>
              </VCol>
              <VCol v-if="service.ipv6_address" cols="12" sm="6">
                <div class="detail-item">
                  <div class="detail-label">IPv6 Address</div>
                  <div class="detail-value">
                    <code>{{ service.ipv6_address }}</code>
                  </div>
                </div>
              </VCol>
              <VCol cols="12" sm="6">
                <div class="detail-item">
                  <div class="detail-label">Access Method</div>
                  <div class="detail-value">
                    <span v-if="service.provisioning_info?.access_method">
                      {{ service.provisioning_info.access_method }}
                    </span>
                    <span v-else-if="service.ipv4_address">
                      SSH via {{ service.ipv4_address }}
                    </span>
                    <span v-else class="text-medium-emphasis">Not available</span>
                  </div>
                </div>
              </VCol>
            </VRow>
          </VCardText>
        </VCard>

        <!-- Game Server Details -->
        <VCard v-if="isGame" class="mb-6" elevation="0">
          <VCardTitle class="d-flex align-center gap-2">
            <VIcon icon="tabler-device-gamepad-2" color="primary" />
            Game Server Information
          </VCardTitle>
          <VCardText>
            <VRow>
              <VCol cols="12" sm="6">
                <div class="detail-item">
                  <div class="detail-label">Connection Address</div>
                  <div class="detail-value">
                    <code v-if="connectionString">{{ connectionString }}</code>
                    <code v-else-if="service.ipv4_address">{{ service.ipv4_address }}</code>
                    <span v-else class="text-medium-emphasis">Not assigned</span>
                  </div>
                </div>
              </VCol>
              <VCol cols="12" sm="6">
                <div class="detail-item">
                  <div class="detail-label">Hostname</div>
                  <div class="detail-value">
                    <code v-if="service.hostname">{{ service.hostname }}</code>
                    <span v-else class="text-medium-emphasis">Not set</span>
                  </div>
                </div>
              </VCol>
              <VCol v-if="service.provisioning_info?.game_type" cols="12" sm="6">
                <div class="detail-item">
                  <div class="detail-label">Game Type</div>
                  <div class="detail-value text-capitalize">
                    {{ service.provisioning_info.game_type }}
                  </div>
                </div>
              </VCol>
              <VCol v-if="service.provisioning_info?.slots || service.provisioning_info?.max_players" cols="12" sm="6">
                <div class="detail-item">
                  <div class="detail-label">Player Slots</div>
                  <div class="detail-value">
                    {{ service.provisioning_info.slots || service.provisioning_info.max_players }}
                  </div>
                </div>
              </VCol>
            </VRow>
          </VCardText>
        </VCard>

        <!-- Web Hosting Details -->
        <VCard v-if="isWebHosting" class="mb-6" elevation="0">
          <VCardTitle class="d-flex align-center gap-2">
            <VIcon icon="tabler-world-www" color="primary" />
            Web Hosting Information
          </VCardTitle>
          <VCardText>
            <VRow>
              <VCol cols="12" sm="6">
                <div class="detail-item">
                  <div class="detail-label">Domain</div>
                  <div class="detail-value">
                    <code v-if="service.domain">{{ service.domain }}</code>
                    <span v-else class="text-medium-emphasis">Not set</span>
                  </div>
                </div>
              </VCol>
              <VCol v-if="service.provisioning_info?.username" cols="12" sm="6">
                <div class="detail-item">
                  <div class="detail-label">Username</div>
                  <div class="detail-value">
                    <code>{{ service.provisioning_info.username }}</code>
                  </div>
                </div>
              </VCol>
              <VCol cols="12" sm="6">
                <div class="detail-item">
                  <div class="detail-label">Server IP</div>
                  <div class="detail-value">
                    <code v-if="service.ipv4_address">{{ service.ipv4_address }}</code>
                    <span v-else class="text-medium-emphasis">Not assigned</span>
                  </div>
                </div>
              </VCol>
              <VCol v-if="service.provisioning_info?.nameservers" cols="12" sm="6">
                <div class="detail-item">
                  <div class="detail-label">Nameservers</div>
                  <div class="detail-value">
                    <code>{{ service.provisioning_info.nameservers }}</code>
                  </div>
                </div>
              </VCol>
            </VRow>
          </VCardText>
        </VCard>

        <!-- Provisioning Information -->
        <VCard v-if="provisioningEntries.length > 0" class="mb-6" elevation="0">
          <VCardTitle class="d-flex align-center gap-2">
            <VIcon icon="tabler-settings" color="primary" />
            Provisioning Information
          </VCardTitle>
          <VCardText>
            <VTable density="comfortable" hover>
              <thead>
                <tr>
                  <th class="text-capitalize font-weight-bold">Property</th>
                  <th class="font-weight-bold">Value</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="entry in provisioningEntries" :key="entry.key">
                  <td class="text-capitalize font-weight-medium">{{ entry.key }}</td>
                  <td><code>{{ entry.value }}</code></td>
                </tr>
              </tbody>
            </VTable>
          </VCardText>
        </VCard>
      </VCol>

      <!-- Sidebar -->
      <VCol cols="12" :lg="isVps && isActive ? 4 : 12" :class="{ 'mt-6 mt-lg-0': isVps && isActive }">
        <div class="sidebar-sticky">
          <!-- Service Overview -->
          <VCard class="mb-6 sidebar-card" elevation="0">
            <VCardTitle class="d-flex align-center gap-2">
              <VIcon icon="tabler-info-circle" color="primary" />
              Overview
            </VCardTitle>
            <VCardText>
              <VList density="compact" class="pa-0">
                <VListItem class="px-0">
                  <template #prepend>
                    <VIcon icon="tabler-hash" size="20" class="me-3 text-medium-emphasis" />
                  </template>
                  <VListItemTitle class="text-caption text-medium-emphasis mb-1">
                    Service ID
                  </VListItemTitle>
                  <VListItemSubtitle class="text-body-1 font-weight-medium">
                    #{{ service.id }}
                  </VListItemSubtitle>
                </VListItem>
                <VListItem v-if="service.platform_service_id" class="px-0">
                  <template #prepend>
                    <VIcon icon="tabler-link" size="20" class="me-3 text-medium-emphasis" />
                  </template>
                  <VListItemTitle class="text-caption text-medium-emphasis mb-1">
                    External ID
                  </VListItemTitle>
                  <VListItemSubtitle class="text-body-1 font-weight-medium">
                    {{ service.platform_service_id }}
                  </VListItemSubtitle>
                </VListItem>
                <VListItem class="px-0">
                  <template #prepend>
                    <VIcon icon="tabler-circle-dot" size="20" class="me-3 text-medium-emphasis" />
                  </template>
                  <VListItemTitle class="text-caption text-medium-emphasis mb-1">
                    Status
                  </VListItemTitle>
                  <VListItemSubtitle>
                    <VChip
                      :color="resolveServiceStatusColor(service.status)"
                      size="small"
                      class="text-capitalize status-indicator mt-1"
                    >
                      <VIcon icon="tabler-circle-filled" size="8" start />
                      {{ service.status }}
                    </VChip>
                  </VListItemSubtitle>
                </VListItem>
              </VList>
            </VCardText>
          </VCard>

          <!-- Important Dates -->
          <VCard class="mb-6 sidebar-card" elevation="0">
            <VCardTitle class="d-flex align-center gap-2">
              <VIcon icon="tabler-calendar" color="primary" />
              Important Dates
            </VCardTitle>
            <VCardText>
              <div class="date-list">
                <div class="date-item">
                  <div class="date-label">Created</div>
                  <div class="date-value">{{ formatDate(service.created_at) }}</div>
                </div>
                <div class="date-item">
                  <div class="date-label">Provisioned</div>
                  <div class="date-value">{{ formatDate(service.provisioned_at) }}</div>
                </div>
                <div v-if="service.subscription?.current_period_end" class="date-item">
                  <div class="date-label">Next Renewal</div>
                  <div class="date-value">{{ formatDate(service.subscription.current_period_end) }}</div>
                </div>
                <div v-if="service.suspended_at" class="date-item">
                  <div class="date-label">Suspended</div>
                  <div class="date-value text-error">{{ formatDate(service.suspended_at) }}</div>
                </div>
                <div v-if="service.terminated_at" class="date-item">
                  <div class="date-label">Terminated</div>
                  <div class="date-value text-error">{{ formatDate(service.terminated_at) }}</div>
                </div>
              </div>
            </VCardText>
          </VCard>

          <!-- Quick Actions -->
          <VCard v-if="!isTerminated" class="sidebar-card" elevation="0">
            <VCardTitle class="d-flex align-center gap-2">
              <VIcon icon="tabler-bolt" color="primary" />
              Quick Actions
            </VCardTitle>
            <VCardText>
              <div class="quick-actions">
                <Link
                  v-if="isActive && service.plan"
                  :href="`/services/${service.id}/upgrade`"
                  class="text-decoration-none"
                >
                  <VBtn block variant="tonal" color="primary" class="text-none mb-3">
                    <VIcon icon="tabler-arrow-up" start />
                    Upgrade / Downgrade
                  </VBtn>
                </Link>

                <VBtn
                  v-if="controlPanelUrl"
                  :href="controlPanelUrl"
                  target="_blank"
                  rel="noopener noreferrer"
                  block
                  variant="tonal"
                  class="text-none mb-3"
                >
                  <VIcon icon="tabler-external-link" start />
                  {{ platformLabel }} Panel
                </VBtn>

                <Link
                  v-if="service.subscription_id"
                  :href="`/subscriptions/${service.subscription_id}`"
                  class="text-decoration-none"
                >
                  <VBtn block variant="tonal" class="text-none mb-3">
                    <VIcon icon="tabler-receipt" start />
                    View Subscription
                  </VBtn>
                </Link>

                <Link href="/tickets/create" class="text-decoration-none">
                  <VBtn block variant="tonal" class="text-none mb-3">
                    <VIcon icon="tabler-headset" start />
                    Get Support
                  </VBtn>
                </Link>

                <Link href="/billing" class="text-decoration-none">
                  <VBtn block variant="tonal" class="text-none">
                    <VIcon icon="tabler-credit-card" start />
                    Billing
                  </VBtn>
                </Link>
              </div>
            </VCardText>
          </VCard>
        </div>
      </VCol>
    </VRow>

    <!-- Rebuild Dialog -->
    <VDialog v-model="rebuildDialog" max-width="600">
      <VCard>
        <VCardTitle class="text-h5 font-weight-bold">
          <VIcon icon="tabler-reload" color="error" class="me-2" />
          Rebuild VPS
        </VCardTitle>
        <VCardText>
          <VAlert type="error" variant="tonal" class="mb-4">
            <VAlertTitle class="font-weight-bold">Warning: Data Loss</VAlertTitle>
            Rebuilding will permanently erase all data on this VPS. This action cannot be undone.
          </VAlert>

          <div class="text-subtitle-2 text-medium-emphasis mb-3">
            SELECT OPERATING SYSTEM
          </div>
          <VRadioGroup v-model="rebuildForm.template_id">
            <VCard
              v-for="template in templates"
              :key="template.id"
              variant="outlined"
              :color="rebuildForm.template_id === template.id ? 'primary' : undefined"
              class="mb-2 template-card"
              @click="rebuildForm.template_id = template.id"
            >
              <VCardText class="d-flex align-center gap-3 pa-3">
                <VRadio :value="template.id" />
                <VIcon :icon="template.icon" size="32" />
                <div class="font-weight-medium">{{ template.name }}</div>
              </VCardText>
            </VCard>
          </VRadioGroup>
        </VCardText>
        <VCardActions>
          <VSpacer />
          <VBtn variant="text" @click="rebuildDialog = false">
            Cancel
          </VBtn>
          <VBtn
            color="error"
            :disabled="!rebuildForm.template_id"
            :loading="rebuildForm.processing"
            @click="submitRebuild"
          >
            <VIcon icon="tabler-alert-triangle" start />
            Rebuild VPS
          </VBtn>
        </VCardActions>
      </VCard>
    </VDialog>

    <!-- New Password Dialog -->
    <VDialog v-model="showPasswordDialog" max-width="440" persistent>
      <VCard>
        <VCardTitle class="text-h6 pa-4">New Root Password</VCardTitle>
        <VCardText>
          <VAlert type="warning" variant="tonal" class="mb-4">
            Copy this password now. It will not be shown again.
          </VAlert>
          <VTextField
            :model-value="newPassword?.new_password ?? ''"
            readonly
            variant="outlined"
            append-inner-icon="tabler-copy"
            @click:append-inner="navigator.clipboard.writeText(newPassword?.new_password ?? '')"
          />
        </VCardText>
        <VCardActions>
          <VSpacer />
          <VBtn color="primary" @click="showPasswordDialog = false">Done</VBtn>
        </VCardActions>
      </VCard>
    </VDialog>
  </div>
</template>

<style scoped>
@import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&display=swap');

/* Service Header */
.service-header {
  background: linear-gradient(135deg, rgba(var(--v-theme-primary), 0.05) 0%, rgba(var(--v-theme-surface), 1) 100%);
  border: 1px solid rgba(var(--v-border-color), var(--v-border-opacity));
  border-radius: 12px;
}

.service-avatar {
  box-shadow: 0 8px 24px rgba(var(--v-theme-primary), 0.2);
  transition: transform 0.3s ease;
}

.service-avatar:hover {
  transform: scale(1.05);
}

/* Status Indicator */
.status-indicator {
  animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.85;
  }
}

/* VPS Control Panel */
.vps-control-panel {
  border: 2px solid rgba(var(--v-theme-primary), 0.2);
  background: linear-gradient(135deg, rgba(var(--v-theme-primary), 0.02) 0%, rgba(var(--v-theme-surface), 1) 100%);
  position: relative;
  overflow: hidden;
}

.vps-control-panel::before {
  content: '';
  position: absolute;
  top: -50%;
  right: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(var(--v-theme-primary), 0.05) 0%, transparent 70%);
  animation: rotate 20s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.vps-control-panel > * {
  position: relative;
  z-index: 1;
}

/* Power Buttons */
.power-btn {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  font-weight: 600;
}

.power-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.15);
}

.power-btn:active {
  transform: translateY(0);
}

/* Server Info Code */
.server-info-code {
  background: rgba(255, 255, 255, 0.2);
  padding: 4px 12px;
  border-radius: 6px;
  font-family: 'Monaco', 'Menlo', monospace;
  font-size: 0.9rem;
  font-weight: 600;
}

/* Detail Items */
.detail-item {
  margin-bottom: 1.5rem;
}

.detail-label {
  font-size: 0.75rem;
  color: rgba(var(--v-theme-on-surface), 0.6);
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  margin-bottom: 0.5rem;
}

.detail-value {
  font-size: 1rem;
  font-weight: 500;
}

.detail-value code {
  background: rgba(var(--v-theme-primary), 0.08);
  padding: 4px 10px;
  border-radius: 6px;
  font-family: 'Monaco', 'Menlo', monospace;
  font-size: 0.875rem;
}

/* Feature Items */
.feature-item {
  display: flex;
  align-items: flex-start;
  padding: 0.75rem;
  background: rgba(var(--v-theme-success), 0.05);
  border-radius: 8px;
  border-left: 3px solid rgb(var(--v-theme-success));
}

/* Sidebar */
.sidebar-sticky {
  position: sticky;
  top: 24px;
}

.sidebar-card {
  border: 1px solid rgba(var(--v-border-color), var(--v-border-opacity));
  transition: all 0.3s ease;
}

.sidebar-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  transform: translateY(-2px);
}

/* Date List */
.date-list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.date-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.75rem;
  background: rgba(var(--v-theme-surface), 0.5);
  border-radius: 8px;
  border-left: 3px solid rgb(var(--v-theme-primary));
}

.date-label {
  font-size: 0.875rem;
  color: rgba(var(--v-theme-on-surface), 0.6);
  font-weight: 500;
}

.date-value {
  font-size: 0.875rem;
  font-weight: 600;
}

/* Quick Actions */
.quick-actions :deep(.v-btn) {
  transition: all 0.2s ease;
}

.quick-actions :deep(.v-btn:hover) {
  transform: translateX(4px);
}

/* Template Cards */
.template-card {
  cursor: pointer;
  transition: all 0.2s ease;
}

.template-card:hover {
  transform: translateX(4px);
  border-color: rgb(var(--v-theme-primary));
}

/* Responsive adjustments */
@media (max-width: 1280px) {
  .sidebar-sticky {
    position: static;
  }
}
</style>
