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

interface Template {
  id: number
  name: string
  os_family?: string
}

interface Props {
  service: Service
  templates: Template[]
}

const props = defineProps<Props>()

const rebuildForm = useForm({
  template_id: null as number | null,
})

const confirmText = ref<string>('')

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` },
])

const canRebuild = computed<boolean>(() => {
  return rebuildForm.template_id !== null && confirmText.value === 'REBUILD'
})

function submitRebuild(): void {
  if (!canRebuild.value) return

  rebuildForm.post(`/services/${props.service.id}/vps/rebuild`, {
    preserveScroll: true,
    onSuccess: () => {
      rebuildForm.reset()
      confirmText.value = ''
    },
  })
}

function resolveOsIcon(name: string): string {
  const lower = name.toLowerCase()
  if (lower.includes('ubuntu')) return 'tabler-brand-ubuntu'
  if (lower.includes('debian')) return 'tabler-brand-debian'
  if (lower.includes('centos') || lower.includes('rocky') || lower.includes('alma') || lower.includes('rhel')) return 'tabler-brand-redhat'
  if (lower.includes('windows')) return 'tabler-brand-windows'
  if (lower.includes('fedora')) return 'tabler-brand-open-source'
  return 'tabler-server'
}
</script>

<template>
  <ServiceTabLayout
    :service="service"
    :tabs="tabs"
    :current-tab="`/services/${service.id}/vps-panel/rebuild`"
  >
    <VCard elevation="0">
      <VCardTitle class="d-flex align-center gap-2">
        <VIcon icon="tabler-reload" color="error" />
        Rebuild Server
      </VCardTitle>
      <VCardText>
        <VAlert type="error" variant="tonal" class="mb-6" prominent>
          <VAlertTitle class="font-weight-bold">Warning: Data Loss</VAlertTitle>
          Rebuilding will permanently erase all data on this VPS. This action cannot be undone.
          Create a snapshot before rebuilding if you want to preserve your data.
        </VAlert>

        <div class="text-subtitle-2 text-medium-emphasis mb-4">SELECT OPERATING SYSTEM</div>

        <VRow v-if="templates.length > 0">
          <VCol
            v-for="template in templates"
            :key="template.id"
            cols="12"
            sm="6"
            md="4"
          >
            <VCard
              variant="outlined"
              :color="rebuildForm.template_id === template.id ? 'primary' : undefined"
              class="cursor-pointer h-100"
              :class="{ 'border-primary': rebuildForm.template_id === template.id }"
              @click="rebuildForm.template_id = template.id"
            >
              <VCardText class="d-flex align-center gap-3 pa-4">
                <VRadio :model-value="rebuildForm.template_id === template.id" :value="true" />
                <VIcon :icon="resolveOsIcon(template.name)" size="28" />
                <div class="font-weight-medium">{{ template.name }}</div>
              </VCardText>
            </VCard>
          </VCol>
        </VRow>

        <VAlert v-else type="info" variant="tonal" class="mb-4">
          No templates available. This feature requires API configuration.
        </VAlert>

        <VDivider class="my-6" />

        <div class="text-subtitle-2 text-medium-emphasis mb-4">TYPE "REBUILD" TO CONFIRM</div>
        <VTextField
          v-model="confirmText"
          label="Type REBUILD to confirm"
          variant="outlined"
          placeholder="REBUILD"
          class="mb-4"
          style="max-width: 300px;"
        />

        <VBtn
          color="error"
          size="large"
          class="text-none"
          :disabled="!canRebuild"
          :loading="rebuildForm.processing"
          @click="submitRebuild"
        >
          <VIcon icon="tabler-alert-triangle" start />
          Rebuild Server
        </VBtn>
      </VCardText>
    </VCard>
  </ServiceTabLayout>
</template>
