<script lang="ts" setup>
import { computed, ref } from 'vue'
import { useForm, router } from '@inertiajs/vue3'
import ServiceTabLayout from '@/Components/Panel/ServiceTabLayout.vue'
import type { Service } from '@/types'

interface Snapshot {
  id: number
  name: string
  size: number
  status: string
  created_at: string
}

interface Props {
  service: Service
  snapshots: Snapshot[]
}

const props = defineProps<Props>()

const showCreateDialog = ref<boolean>(false)

const form = useForm({
  name: '',
})

const tabs = computed(() => [
  { label: 'Dashboard', icon: 'tabler-dashboard', to: `/services/${props.service.id}/vps-panel` },
  { label: 'Console', icon: 'tabler-terminal-2', to: `/services/${props.service.id}/vps-panel/console` },
  { label: 'Graphs', icon: 'tabler-chart-line', to: `/services/${props.service.id}/vps-panel/graphs` },
  { label: 'Firewall', icon: 'tabler-shield', to: `/services/${props.service.id}/vps-panel/firewall` },
  { label: 'Snapshots', icon: 'tabler-camera', to: `/services/${props.service.id}/vps-panel/snapshots` },
  { label: 'Backups', icon: 'tabler-database', to: `/services/${props.service.id}/vps-panel/backups` },
  { label: 'Network', icon: 'tabler-network', to: `/services/${props.service.id}/vps-panel/network` },
  { label: 'Rebuild', icon: 'tabler-reload', to: `/services/${props.service.id}/vps-panel/rebuild` },
  { label: 'Settings', icon: 'tabler-settings', to: `/services/${props.service.id}/vps-panel/settings` },
  { label: 'Activity', icon: 'tabler-history', to: `/services/${props.service.id}/vps-panel/activity` },
])

function formatSize(bytes: number): string {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`
}

function formatDate(dateStr: string): string {
  return new Date(dateStr).toLocaleString()
}

function createSnapshot(): void {
  form.post(`/services/${props.service.id}/vps-panel/snapshots`, {
    preserveScroll: true,
    onSuccess: () => {
      showCreateDialog.value = false
      form.reset()
    },
  })
}

function restoreSnapshot(snapshotId: number): void {
  if (confirm('Are you sure? Restoring a snapshot will replace the current server state.')) {
    router.post(`/services/${props.service.id}/vps-panel/snapshots/${snapshotId}/restore`, {}, {
      preserveScroll: true,
    })
  }
}

function deleteSnapshot(snapshotId: number): void {
  if (confirm('Are you sure you want to delete this snapshot?')) {
    router.delete(`/services/${props.service.id}/vps-panel/snapshots/${snapshotId}`, {
      preserveScroll: true,
    })
  }
}
</script>

<template>
  <ServiceTabLayout
    :service="service"
    :tabs="tabs"
    :current-tab="`/services/${service.id}/vps-panel/snapshots`"
  >
    <VCard elevation="0">
      <VCardTitle class="d-flex align-center justify-space-between">
        <div class="d-flex align-center gap-2">
          <VIcon icon="tabler-camera" color="primary" />
          Snapshots
        </div>
        <VBtn color="primary" class="text-none" @click="showCreateDialog = true">
          <VIcon icon="tabler-plus" start />
          Create Snapshot
        </VBtn>
      </VCardTitle>
      <VCardText>
        <VTable v-if="snapshots.length > 0" hover>
          <thead>
            <tr>
              <th class="font-weight-bold">Name</th>
              <th class="font-weight-bold">Size</th>
              <th class="font-weight-bold">Status</th>
              <th class="font-weight-bold">Created</th>
              <th class="text-end font-weight-bold">Actions</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="snapshot in snapshots" :key="snapshot.id">
              <td class="font-weight-medium">{{ snapshot.name }}</td>
              <td>{{ formatSize(snapshot.size) }}</td>
              <td>
                <VChip
                  :color="snapshot.status === 'complete' ? 'success' : 'warning'"
                  size="small"
                  class="text-capitalize"
                >
                  {{ snapshot.status }}
                </VChip>
              </td>
              <td>{{ formatDate(snapshot.created_at) }}</td>
              <td class="text-end">
                <VBtn
                  icon="tabler-history"
                  variant="text"
                  color="primary"
                  size="small"
                  title="Restore"
                  class="me-1"
                  @click="restoreSnapshot(snapshot.id)"
                />
                <VBtn
                  icon="tabler-trash"
                  variant="text"
                  color="error"
                  size="small"
                  title="Delete"
                  @click="deleteSnapshot(snapshot.id)"
                />
              </td>
            </tr>
          </tbody>
        </VTable>

        <div v-else class="text-center pa-8 text-medium-emphasis">
          <VIcon icon="tabler-camera-off" size="48" class="mb-2" />
          <div class="text-body-1 mb-2">No snapshots</div>
          <div class="text-body-2">Create a snapshot to save the current state of your server.</div>
        </div>
      </VCardText>
    </VCard>

    <!-- Create Snapshot Dialog -->
    <VDialog v-model="showCreateDialog" max-width="450">
      <VCard>
        <VCardTitle class="text-h6 font-weight-bold">
          <VIcon icon="tabler-camera" color="primary" class="me-2" />
          Create Snapshot
        </VCardTitle>
        <VCardText>
          <VTextField
            v-model="form.name"
            label="Snapshot Name"
            variant="outlined"
            placeholder="e.g., Before update"
            :error-messages="form.errors.name"
          />
        </VCardText>
        <VCardActions>
          <VSpacer />
          <VBtn variant="text" @click="showCreateDialog = false">Cancel</VBtn>
          <VBtn
            color="primary"
            :loading="form.processing"
            :disabled="!form.name"
            @click="createSnapshot"
          >
            Create
          </VBtn>
        </VCardActions>
      </VCard>
    </VDialog>
  </ServiceTabLayout>
</template>
