<template>
  <div class="flex flex-col h-full">
    <LayoutHeader>
      <template #left>
        <div class="flex items-center gap-3">
          <Button variant="ghost" @click="$router.push({ name: 'Sites' })">
            <FeatherIcon name="arrow-left" class="h-4 w-4" />
          </Button>
          <div v-if="detail.loading && !site">
            <div class="h-5 w-40 bg-surface-gray-2 rounded animate-pulse"></div>
            <div class="h-4 w-24 bg-surface-gray-2 rounded animate-pulse mt-1"></div>
          </div>
          <div v-else>
            <h1 class="text-xl font-semibold text-ink-gray-9">
              {{ site?.name }}
            </h1>
            <p class="text-sm text-ink-gray-5">
              {{ site?.container_name }}
            </p>
          </div>
          <Badge
            v-if="site"
            :variant="getStatusBadge(site.status)"
            :label="site.status"
          />
        </div>
      </template>
      <template #right>
        <Button
          v-if="site?.status !== 'Running'"
          variant="subtle"
          @click="startSite"
          :loading="actionLoading === 'start'"
        >
          <template #prefix>
            <FeatherIcon name="play" class="h-4 w-4" />
          </template>
          {{ $t('sites.actions.start') }}
        </Button>
        <Button
          v-if="site?.status === 'Running'"
          variant="subtle"
          @click="stopSite"
          :loading="actionLoading === 'stop'"
        >
          <template #prefix>
            <FeatherIcon name="square" class="h-4 w-4" />
          </template>
          {{ $t('sites.actions.stop') }}
        </Button>
        <Button
          variant="subtle"
          @click="restartSite"
          :loading="actionLoading === 'restart'"
        >
          <template #prefix>
            <FeatherIcon name="rotate-cw" class="h-4 w-4" />
          </template>
          {{ $t('sites.actions.restart') }}
        </Button>
        <Button
          variant="subtle"
          @click="openUpdateModal"
        >
          <template #prefix>
            <FeatherIcon name="download" class="h-4 w-4" />
          </template>
          Update
        </Button>
        <Button variant="solid" @click="openSite">
          <template #prefix>
            <FeatherIcon name="external-link" class="h-4 w-4" />
          </template>
          {{ $t('sites.actions.openSite') }}
        </Button>
      </template>
    </LayoutHeader>

    <div class="flex-1 overflow-auto">
      <!-- Tabs -->
      <div class="border-b px-5">
        <nav class="flex gap-2">
          <button
            v-for="tab in tabs"
            :key="tab.id"
            class="px-4 py-2 text-sm font-medium transition-colors"
            :class="
              activeTab === tab.id
                ? 'border-b-2 border-ink-gray-9 text-ink-gray-9'
                : 'text-ink-gray-5 hover:text-ink-gray-7'
            "
            @click="activeTab = tab.id"
          >
            {{ $t(tab.label) }}
          </button>
        </nav>
      </div>

      <div class="p-5">
        <!-- Loading state (only on initial load) -->
        <div v-if="detail.loading && !site" class="flex items-center justify-center h-64">
          <Spinner class="h-8 w-8" />
        </div>

        <!-- Error state (only when no data at all) -->
        <div v-else-if="detail.error && !site" class="flex flex-col items-center justify-center h-64 gap-3">
          <FeatherIcon name="alert-circle" class="h-10 w-10 text-red-500" />
          <p class="text-sm text-ink-gray-5">Failed to load container details</p>
          <Button variant="subtle" @click="detail.reload()">Retry</Button>
        </div>

        <!-- Tab content -->
        <template v-else>
          <!-- Overview Tab -->
          <div v-show="activeTab === 'overview'">
            <div class="grid gap-6 lg:grid-cols-2">
              <!-- Container Information -->
              <div class="rounded-lg border p-5">
                <h2 class="text-lg font-semibold text-ink-gray-9 mb-4">
                  Container Information
                </h2>
                <div class="space-y-3">
                  <div class="flex justify-between py-2 border-b">
                    <span class="text-sm text-ink-gray-5">IP Address</span>
                    <span class="text-sm font-medium font-mono text-ink-gray-9">{{ site?.ip_address || '-' }}</span>
                  </div>
                  <div class="flex justify-between py-2 border-b">
                    <span class="text-sm text-ink-gray-5">Image</span>
                    <span class="text-sm font-medium text-ink-gray-9">{{ site?.image || '-' }}</span>
                  </div>
                  <div class="flex justify-between py-2 border-b">
                    <span class="text-sm text-ink-gray-5">Architecture</span>
                    <span class="text-sm font-medium text-ink-gray-9">{{ site?.architecture || '-' }}</span>
                  </div>
                  <div class="flex justify-between py-2 border-b">
                    <span class="text-sm text-ink-gray-5">Type</span>
                    <span class="text-sm font-medium text-ink-gray-9">{{ site?.type || '-' }}</span>
                  </div>
                  <div class="flex justify-between py-2 border-b">
                    <span class="text-sm text-ink-gray-5">Owner</span>
                    <span class="text-sm font-medium text-ink-gray-9">{{ site?.owner || '-' }}</span>
                  </div>
                  <div class="flex justify-between py-2 border-b">
                    <span class="text-sm text-ink-gray-5">Created</span>
                    <span class="text-sm font-medium text-ink-gray-9">{{ site?.created || '-' }}</span>
                  </div>
                  <div class="flex justify-between py-2">
                    <span class="text-sm text-ink-gray-5">Uptime</span>
                    <span class="text-sm font-medium text-ink-gray-9">{{ site?.uptime || '-' }}</span>
                  </div>
                </div>
              </div>

              <!-- Resource Usage -->
              <div class="rounded-lg border p-5">
                <h2 class="text-lg font-semibold text-ink-gray-9 mb-4">
                  Resource Usage
                </h2>
                <div v-if="site?.status === 'Running'" class="space-y-4">
                  <div>
                    <div class="flex justify-between text-sm mb-1">
                      <span class="text-ink-gray-5">CPU</span>
                      <span class="text-ink-gray-9 font-medium">{{ site?.cpu_usage || 0 }}%</span>
                    </div>
                    <div class="w-full bg-surface-gray-2 rounded-full h-2">
                      <div
                        class="bg-blue-500 h-2 rounded-full transition-all"
                        :style="{ width: `${site?.cpu_usage || 0}%` }"
                      ></div>
                    </div>
                  </div>
                  <div>
                    <div class="flex justify-between text-sm mb-1">
                      <span class="text-ink-gray-5">RAM</span>
                      <span class="text-ink-gray-9 font-medium">{{ site?.ram_usage || 0 }}%</span>
                    </div>
                    <div class="w-full bg-surface-gray-2 rounded-full h-2">
                      <div
                        class="bg-purple-500 h-2 rounded-full transition-all"
                        :style="{ width: `${site?.ram_usage || 0}%` }"
                      ></div>
                    </div>
                    <p class="text-xs text-ink-gray-4 mt-1">
                      {{ formatBytes(site?.memory_usage_bytes) }} / {{ formatBytes(site?.memory_total_bytes) }}
                    </p>
                  </div>
                  <div>
                    <div class="flex justify-between text-sm mb-1">
                      <span class="text-ink-gray-5">Disk</span>
                      <span class="text-ink-gray-9 font-medium">{{ site?.disk_usage || 0 }}%</span>
                    </div>
                    <div class="w-full bg-surface-gray-2 rounded-full h-2">
                      <div
                        class="bg-orange-500 h-2 rounded-full transition-all"
                        :style="{ width: `${site?.disk_usage || 0}%` }"
                      ></div>
                    </div>
                    <p class="text-xs text-ink-gray-4 mt-1">
                      {{ formatBytes(site?.disk_usage_bytes) }} / {{ formatBytes(site?.disk_total_bytes) }}
                    </p>
                  </div>
                  <div class="grid grid-cols-2 gap-4 pt-2 border-t text-sm">
                    <div>
                      <p class="text-ink-gray-4 text-xs">Network RX</p>
                      <p class="font-medium text-ink-gray-9">{{ formatBytes(site?.network_rx) }}</p>
                    </div>
                    <div>
                      <p class="text-ink-gray-4 text-xs">Network TX</p>
                      <p class="font-medium text-ink-gray-9">{{ formatBytes(site?.network_tx) }}</p>
                    </div>
                  </div>
                  <div class="text-sm text-ink-gray-5">
                    Processes: <span class="font-medium text-ink-gray-9">{{ site?.connections || 0 }}</span>
                  </div>
                </div>
                <div v-else class="flex items-center justify-center h-32 text-ink-gray-4 text-sm">
                  Container is not running
                </div>
              </div>
            </div>
          </div>

          <!-- Activity Tab -->
          <div v-show="activeTab === 'activity'">
            <div class="mb-3 text-xs text-ink-gray-4 bg-yellow-50 border border-yellow-200 rounded p-2">
              Activity tracking is coming soon. Showing placeholder data.
            </div>
            <div class="rounded-lg border overflow-hidden">
              <div v-if="siteActivity.length" class="divide-y">
                <div
                  v-for="activity in siteActivity"
                  :key="activity.id"
                  class="p-4 flex items-start gap-4"
                >
                  <div
                    class="flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center"
                    :class="activityIconClasses[activity.type] || 'bg-surface-gray-2 text-ink-gray-5'"
                  >
                    <FeatherIcon :name="activityIcons[activity.type] || 'settings'" class="h-4 w-4" />
                  </div>
                  <div class="flex-1 min-w-0">
                    <p class="text-sm text-ink-gray-9">{{ activity.message }}</p>
                    <p class="text-xs text-ink-gray-4 mt-1">
                      {{ activity.timestamp }} - {{ activity.user }}
                    </p>
                  </div>
                </div>
              </div>
              <div v-else class="p-8 text-center text-sm text-ink-gray-4">
                No activity recorded yet
              </div>
            </div>
          </div>

          <!-- Logs Tab -->
          <div v-show="activeTab === 'logs'">
            <div class="flex justify-end mb-3">
              <Button variant="subtle" size="sm" @click="loadLogs" :loading="containerLogs.loading">
                <template #prefix>
                  <FeatherIcon name="refresh-cw" class="h-3 w-3" />
                </template>
                Refresh Logs
              </Button>
            </div>
            <div v-if="containerLogs.error" class="text-sm text-red-500 bg-red-50 p-2 rounded mb-3">
              Error: {{ containerLogs.error }}
            </div>
            <div class="bg-gray-900 rounded-lg p-4 font-mono text-sm overflow-x-auto min-h-[200px]">
              <div v-if="containerLogs.loading && !logEntries.length" class="flex items-center justify-center py-8">
                <Spinner class="h-6 w-6 text-gray-400" />
              </div>
              <div v-else-if="logEntries.length">
                <div
                  v-for="(log, idx) in logEntries"
                  :key="idx"
                  class="flex gap-4 py-1"
                >
                  <span
                    v-if="log.source"
                    class="text-gray-600 flex-shrink-0 text-xs"
                  >[{{ log.source }}]</span>
                  <span
                    class="flex-shrink-0 w-16"
                    :class="{
                      'text-green-400': log.level === 'info',
                      'text-yellow-400': log.level === 'warning',
                      'text-red-400': log.level === 'error',
                    }"
                  >
                    [{{ log.level.toUpperCase() }}]
                  </span>
                  <span class="text-gray-300">{{ log.message }}</span>
                </div>
              </div>
              <div v-else class="text-gray-500 text-center py-4">No logs available</div>
            </div>
          </div>

          <!-- Snapshots (Backups) Tab -->
          <div v-show="activeTab === 'backups'">
            <div class="flex justify-between items-center mb-4">
              <div class="flex items-center gap-3">
                <h3 class="text-lg font-semibold text-ink-gray-9">
                  Snapshots
                </h3>
                <Button variant="ghost" size="sm" @click="loadSnapshots" :loading="snapshots.loading">
                  <FeatherIcon name="refresh-cw" class="h-3 w-3" />
                </Button>
              </div>
              <Button variant="solid" @click="openSnapshotModal">
                <template #prefix>
                  <FeatherIcon name="plus" class="h-4 w-4" />
                </template>
                Create Snapshot
              </Button>
            </div>

            <!-- Snapshot error -->
            <div v-if="snapshotError" class="text-sm text-red-500 bg-red-50 p-2 rounded mb-3">
              {{ snapshotError }}
            </div>

            <div v-if="snapshots.loading && !snapshotList.length" class="flex items-center justify-center h-32">
              <Spinner class="h-6 w-6" />
            </div>

            <div v-else-if="snapshots.error" class="text-sm text-red-500 bg-red-50 p-2 rounded">
              Failed to load snapshots: {{ snapshots.error }}
            </div>

            <div v-else-if="snapshotList.length" class="rounded-lg border overflow-hidden">
              <table class="min-w-full divide-y">
                <thead class="bg-surface-gray-2">
                  <tr>
                    <th class="px-6 py-3 text-left text-xs font-medium text-ink-gray-5 uppercase">Name</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-ink-gray-5 uppercase">Created</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-ink-gray-5 uppercase">Stateful</th>
                    <th class="px-6 py-3 text-right text-xs font-medium text-ink-gray-5 uppercase">Actions</th>
                  </tr>
                </thead>
                <tbody class="divide-y">
                  <tr v-for="snap in snapshotList" :key="snap.name">
                    <td class="px-6 py-4 text-sm text-ink-gray-9">{{ snap.name }}</td>
                    <td class="px-6 py-4 text-sm text-ink-gray-7">{{ formatDate(snap.created_at) }}</td>
                    <td class="px-6 py-4">
                      <Badge
                        :variant="snap.stateful ? 'info' : 'subtle'"
                        :label="snap.stateful ? 'stateful' : 'stateless'"
                      />
                    </td>
                    <td class="px-6 py-4 text-right">
                      <div class="flex items-center justify-end gap-2">
                        <Button variant="ghost" size="sm" @click="restoreSnapshotAction(snap)" :loading="actionLoading === 'restore-' + snap.name">
                          <FeatherIcon name="rotate-ccw" class="h-4 w-4" />
                        </Button>
                        <Button variant="ghost" size="sm" @click="deleteSnapshotAction(snap)" :loading="actionLoading === 'delete-snap-' + snap.name">
                          <FeatherIcon name="trash-2" class="h-4 w-4 text-red-500" />
                        </Button>
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>

            <div v-else class="rounded-lg border p-8 text-center text-sm text-ink-gray-4">
              No snapshots yet. Create one to backup this container.
            </div>
          </div>
        </template>
      </div>
    </div>

    <!-- Create Snapshot Modal -->
    <Dialog v-model="showSnapshotModal" :options="{ title: 'Create Snapshot' }">
      <template #body-content>
        <div class="space-y-4">
          <FormControl
            v-model="snapshotName"
            label="Snapshot Name"
            type="text"
            required
            placeholder="e.g., backup-2024-01-15"
          />
          <div class="flex items-center gap-2">
            <input
              id="stateful"
              v-model="snapshotStateful"
              type="checkbox"
              class="h-4 w-4 rounded border-gray-300"
            />
            <label for="stateful" class="text-sm text-ink-gray-7">
              Stateful (include memory state - container must be running)
            </label>
          </div>
          <div v-if="snapshotCreateError" class="text-sm text-red-500 bg-red-50 p-2 rounded">
            {{ snapshotCreateError }}
          </div>
        </div>
      </template>
      <template #actions>
        <Button variant="subtle" @click="showSnapshotModal = false">
          {{ $t('common.cancel') }}
        </Button>
        <Button variant="solid" @click="createSnapshotAction" :loading="actionLoading === 'create-snap'">
          Create
        </Button>
      </template>
    </Dialog>

    <!-- Update/Rebuild Modal -->
    <Dialog v-model="showUpdateModal" :options="{ title: 'Update Container' }">
      <template #body-content>
        <div class="space-y-4">
          <div class="text-sm text-ink-gray-6 bg-blue-50 border border-blue-200 rounded p-3">
            <p class="font-medium text-blue-700 mb-1">What is rebuild?</p>
            <p>Rebuild recreates the container from a new image while <strong>preserving attached storage volumes</strong>. Your data will be kept.</p>
          </div>

          <div class="text-sm">
            <span class="text-ink-gray-5">Current image:</span>
            <span class="ml-2 font-medium text-ink-gray-8">{{ site?.image || '-' }}</span>
          </div>

          <div v-if="images.loading" class="flex items-center gap-2 text-sm text-ink-gray-5 py-2">
            <Spinner class="h-4 w-4" /> Loading images...
          </div>
          <FormControl
            v-else
            v-model="updateImage"
            label="New Image"
            type="select"
            :options="imageOptions"
          />

          <div v-if="updateError" class="text-sm text-red-500 bg-red-50 p-2 rounded">
            {{ updateError }}
          </div>
        </div>
      </template>
      <template #actions>
        <Button variant="subtle" @click="showUpdateModal = false">
          {{ $t('common.cancel') }}
        </Button>
        <Button variant="solid" @click="rebuildContainer" :loading="rebuilding">
          Update
        </Button>
      </template>
    </Dialog>

    <!-- Rebuild Progress/Result Modal -->
    <Dialog v-model="showRebuildProgress" :options="{ title: rebuilding ? 'Updating...' : 'Update Result', size: 'lg' }">
      <template #body-content>
        <div class="space-y-4">
          <!-- Progress indicator during rebuild -->
          <div v-if="rebuilding" class="flex flex-col items-center gap-4 py-6">
            <Spinner class="h-10 w-10 text-blue-500" />
            <div class="text-center">
              <p class="text-sm font-medium text-ink-gray-8">Rebuilding container...</p>
              <p class="text-xs text-ink-gray-5 mt-1">This may take a few minutes</p>
            </div>
            <div class="w-full bg-surface-gray-2 rounded-full h-2 overflow-hidden">
              <div class="h-full bg-blue-500 rounded-full animate-pulse" style="width: 60%"></div>
            </div>
          </div>

          <!-- Result after rebuild completes -->
          <template v-else>
            <div class="flex items-center gap-3">
              <FeatherIcon
                v-if="rebuildResult.success"
                name="check-circle"
                class="h-6 w-6 text-green-600"
              />
              <FeatherIcon
                v-else
                name="x-circle"
                class="h-6 w-6 text-red-600"
              />
              <span class="text-sm font-medium" :class="rebuildResult.success ? 'text-green-700' : 'text-red-700'">
                {{ rebuildResult.message }}
              </span>
            </div>

            <!-- Rebuild logs -->
            <div v-if="rebuildResult.logs?.length" class="mt-4">
              <p class="text-xs font-medium text-ink-gray-5 uppercase mb-2">Rebuild Logs</p>
              <div class="bg-surface-gray-1 rounded-lg p-3 max-h-64 overflow-y-auto font-mono text-xs">
                <div
                  v-for="(log, idx) in rebuildResult.logs"
                  :key="idx"
                  class="py-0.5"
                  :class="{
                    'text-green-600': log.includes('✓'),
                    'text-red-600': log.includes('✗') || log.includes('Error'),
                    'text-ink-gray-6': !log.includes('✓') && !log.includes('✗'),
                    'font-semibold': log.includes('==='),
                  }"
                >
                  {{ log }}
                </div>
              </div>
            </div>
          </template>
        </div>
      </template>
      <template #actions>
        <Button
          v-if="!rebuilding"
          variant="solid"
          @click="showRebuildProgress = false; detail.reload()"
        >
          Close
        </Button>
      </template>
    </Dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useRoute } from 'vue-router'
import { createResource, call } from 'frappe-ui'
import { Button, Badge, Spinner, FormControl, Dialog, FeatherIcon } from 'frappe-ui'
import LayoutHeader from '@/components/Common/LayoutHeader.vue'
import { siteActivity } from '@/mocks/sites'

const route = useRoute()
const activeTab = ref('overview')

// Get server from query param (for remote containers)
const targetServer = computed(() => route.query.server || null)
const actionLoading = ref('')
const showSnapshotModal = ref(false)
const snapshotName = ref('')
const snapshotStateful = ref(false)
const snapshotError = ref('')
const snapshotCreateError = ref('')
const logsLoaded = ref(false)
const snapshotsLoaded = ref(false)

// Update/Rebuild state
const showUpdateModal = ref(false)
const updateImage = ref('')
const updateError = ref('')
const rebuilding = ref(false)
const showRebuildProgress = ref(false)
const rebuildResult = ref({ success: false, message: '', logs: [] })

const tabs = [
  { id: 'overview', label: 'sites.detail.overview' },
  { id: 'activity', label: 'sites.detail.activity' },
  { id: 'logs', label: 'sites.detail.logs' },
  { id: 'backups', label: 'sites.detail.backups' },
]

const detail = createResource({
  url: 'admin_panel.api.sites.get_container_detail',
  params: {
    container_name: route.params.siteId,
    target_server: route.query.server || null,
  },
  auto: true,
})

const containerLogs = createResource({
  url: 'admin_panel.api.sites.get_container_logs',
  params: {
    container_name: route.params.siteId,
    target_server: route.query.server || null,
  },
  auto: false,
})

const snapshots = createResource({
  url: 'admin_panel.api.sites.get_snapshots',
  params: {
    container_name: route.params.siteId,
    target_server: route.query.server || null,
  },
  auto: false,
})

const images = createResource({
  url: 'admin_panel.api.sites.get_images',
  params: {
    target_server: route.query.server || null,
  },
  auto: false,
})

const site = computed(() => detail.data)

const imageOptions = computed(() => {
  const list = images.data || []
  return list.map(img => ({
    label: img.alias || img.description || img.fingerprint?.slice(0, 12) || 'Unknown',
    value: img.alias || img.fingerprint,
  }))
})
const logEntries = computed(() => containerLogs.data || [])
const snapshotList = computed(() => snapshots.data || [])

// Lazy load data when tabs are opened
watch(activeTab, (val) => {
  if (val === 'logs' && !logsLoaded.value) {
    loadLogs()
    logsLoaded.value = true
  }
  if (val === 'backups' && !snapshotsLoaded.value) {
    loadSnapshots()
    snapshotsLoaded.value = true
  }
})

function loadLogs() {
  containerLogs.reload()
}

function loadSnapshots() {
  snapshotError.value = ''
  snapshots.reload()
}

function getStatusBadge(status) {
  return { Running: 'success', Stopped: 'warning', Error: 'error', Creating: 'info' }[status] || 'subtle'
}

const activityIcons = {
  start: 'power', stop: 'power', restart: 'refresh-cw',
  backup: 'database', update: 'refresh-cw', config: 'settings',
}
const activityIconClasses = {
  start: 'bg-green-100 text-green-600',
  stop: 'bg-red-100 text-red-600',
  restart: 'bg-blue-100 text-blue-600',
  backup: 'bg-purple-100 text-purple-600',
  update: 'bg-orange-100 text-orange-600',
  config: 'bg-surface-gray-2 text-ink-gray-5',
}

function formatBytes(bytes) {
  if (!bytes) return '0 B'
  const units = ['B', 'KB', 'MB', 'GB', 'TB']
  let i = 0
  let val = bytes
  while (val >= 1024 && i < units.length - 1) {
    val /= 1024
    i++
  }
  return `${val.toFixed(1)} ${units[i]}`
}

function formatDate(dateStr) {
  if (!dateStr) return '-'
  try {
    const d = new Date(dateStr)
    return d.toLocaleString()
  } catch {
    return dateStr
  }
}

function generateDefaultSnapshotName() {
  const now = new Date()
  const y = now.getFullYear()
  const m = String(now.getMonth() + 1).padStart(2, '0')
  const d = String(now.getDate()).padStart(2, '0')
  const h = String(now.getHours()).padStart(2, '0')
  const min = String(now.getMinutes()).padStart(2, '0')
  return `snap-${y}${m}${d}-${h}${min}`
}

async function startSite() {
  actionLoading.value = 'start'
  try {
    await call('admin_panel.api.sites.start_container', {
      container_name: route.params.siteId,
      target_server: targetServer.value,
    })
    detail.reload()
  } catch (e) {
    console.error('Failed to start container:', e)
  } finally {
    actionLoading.value = ''
  }
}

async function stopSite() {
  actionLoading.value = 'stop'
  try {
    await call('admin_panel.api.sites.stop_container', {
      container_name: route.params.siteId,
      target_server: targetServer.value,
    })
    detail.reload()
  } catch (e) {
    console.error('Failed to stop container:', e)
  } finally {
    actionLoading.value = ''
  }
}

async function restartSite() {
  actionLoading.value = 'restart'
  try {
    await call('admin_panel.api.sites.restart_container', {
      container_name: route.params.siteId,
      target_server: targetServer.value,
    })
    detail.reload()
  } catch (e) {
    console.error('Failed to restart container:', e)
  } finally {
    actionLoading.value = ''
  }
}

function openSite() {
  if (site.value?.ip_address) {
    window.open(`http://${site.value.ip_address}`, '_blank')
  }
}

function openSnapshotModal() {
  snapshotName.value = generateDefaultSnapshotName()
  snapshotStateful.value = false
  snapshotCreateError.value = ''
  showSnapshotModal.value = true
}

async function createSnapshotAction() {
  snapshotCreateError.value = ''

  if (!snapshotName.value) {
    snapshotCreateError.value = 'Snapshot name is required'
    return
  }

  actionLoading.value = 'create-snap'
  try {
    await call('admin_panel.api.sites.create_snapshot', {
      container_name: route.params.siteId,
      snapshot_name: snapshotName.value,
      stateful: snapshotStateful.value,
    })
    showSnapshotModal.value = false
    snapshotName.value = ''
    snapshotStateful.value = false
    loadSnapshots()
  } catch (e) {
    console.error('Failed to create snapshot:', e)
    snapshotCreateError.value = e.message || e.exc || 'Failed to create snapshot'
  } finally {
    actionLoading.value = ''
  }
}

async function restoreSnapshotAction(snap) {
  if (!confirm(`Restore container from snapshot "${snap.name}"? This will overwrite the current state.`)) return
  snapshotError.value = ''
  actionLoading.value = 'restore-' + snap.name
  try {
    await call('admin_panel.api.sites.restore_snapshot', {
      container_name: route.params.siteId,
      snapshot_name: snap.name,
    })
    detail.reload()
  } catch (e) {
    console.error('Failed to restore snapshot:', e)
    snapshotError.value = e.message || e.exc || 'Failed to restore snapshot'
  } finally {
    actionLoading.value = ''
  }
}

async function deleteSnapshotAction(snap) {
  if (!confirm(`Delete snapshot "${snap.name}"?`)) return
  snapshotError.value = ''
  actionLoading.value = 'delete-snap-' + snap.name
  try {
    await call('admin_panel.api.sites.delete_snapshot', {
      container_name: route.params.siteId,
      snapshot_name: snap.name,
    })
    loadSnapshots()
  } catch (e) {
    console.error('Failed to delete snapshot:', e)
    snapshotError.value = e.message || e.exc || 'Failed to delete snapshot'
  } finally {
    actionLoading.value = ''
  }
}

function openUpdateModal() {
  updateError.value = ''
  updateImage.value = ''
  showUpdateModal.value = true
  // Load images if not loaded
  if (!images.data) {
    images.reload()
  }
}

async function rebuildContainer() {
  updateError.value = ''

  if (!updateImage.value) {
    updateError.value = 'Please select an image'
    return
  }

  showUpdateModal.value = false
  rebuilding.value = true
  rebuildResult.value = { success: false, message: '', logs: [] }
  showRebuildProgress.value = true

  try {
    const resp = await call('admin_panel.api.sites.rebuild_container', {
      container_name: route.params.siteId,
      image: updateImage.value,
    })

    rebuilding.value = false
    rebuildResult.value = {
      success: resp.success,
      message: resp.message,
      logs: resp.logs || [],
    }
  } catch (e) {
    console.error('Failed to rebuild container:', e)
    rebuilding.value = false
    rebuildResult.value = {
      success: false,
      message: e.message || e.exc || 'Rebuild failed',
      logs: [`Error: ${e.message || e.exc}`],
    }
  }
}
</script>
