<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 FirewallRule {
  id: number
  protocol: string
  port: string | null
  source: string
  action: string
}

interface Props {
  service: Service
  rules: FirewallRule[]
}

const props = defineProps<Props>()

const showAddDialog = ref<boolean>(false)

const form = useForm({
  protocol: 'tcp',
  port: '',
  source: '0.0.0.0/0',
  action: 'accept',
})

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 submitRule(): void {
  form.post(`/services/${props.service.id}/vps-panel/firewall`, {
    preserveScroll: true,
    onSuccess: () => {
      showAddDialog.value = false
      form.reset()
    },
  })
}

function deleteRule(ruleId: number): void {
  if (confirm('Are you sure you want to delete this firewall rule?')) {
    router.delete(`/services/${props.service.id}/vps-panel/firewall/${ruleId}`, {
      preserveScroll: true,
    })
  }
}

function resolveActionColor(action: string): string {
  if (action === 'accept') return 'success'
  if (action === 'drop') return 'error'
  return 'warning'
}
</script>

<template>
  <ServiceTabLayout
    :service="service"
    :tabs="tabs"
    :current-tab="`/services/${service.id}/vps-panel/firewall`"
  >
    <VCard elevation="0">
      <VCardTitle class="d-flex align-center justify-space-between">
        <div class="d-flex align-center gap-2">
          <VIcon icon="tabler-shield" color="primary" />
          Firewall Rules
        </div>
        <VBtn color="primary" class="text-none" @click="showAddDialog = true">
          <VIcon icon="tabler-plus" start />
          Add Rule
        </VBtn>
      </VCardTitle>
      <VCardText>
        <VTable v-if="rules.length > 0" hover>
          <thead>
            <tr>
              <th class="font-weight-bold">Protocol</th>
              <th class="font-weight-bold">Port</th>
              <th class="font-weight-bold">Source</th>
              <th class="font-weight-bold">Action</th>
              <th class="text-end font-weight-bold">Actions</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="rule in rules" :key="rule.id">
              <td class="text-uppercase font-weight-medium">{{ rule.protocol }}</td>
              <td><code>{{ rule.port ?? 'All' }}</code></td>
              <td><code>{{ rule.source }}</code></td>
              <td>
                <VChip :color="resolveActionColor(rule.action)" size="small" class="text-capitalize">
                  {{ rule.action }}
                </VChip>
              </td>
              <td class="text-end">
                <VBtn
                  icon="tabler-trash"
                  variant="text"
                  color="error"
                  size="small"
                  @click="deleteRule(rule.id)"
                />
              </td>
            </tr>
          </tbody>
        </VTable>

        <div v-else class="text-center pa-8 text-medium-emphasis">
          <VIcon icon="tabler-shield-off" size="48" class="mb-2" />
          <div class="text-body-1 mb-2">No firewall rules configured</div>
          <div class="text-body-2">Add rules to control inbound traffic to your server.</div>
        </div>
      </VCardText>
    </VCard>

    <!-- Add Rule Dialog -->
    <VDialog v-model="showAddDialog" max-width="500">
      <VCard>
        <VCardTitle class="text-h6 font-weight-bold">
          <VIcon icon="tabler-shield-plus" color="primary" class="me-2" />
          Add Firewall Rule
        </VCardTitle>
        <VCardText>
          <VSelect
            v-model="form.protocol"
            :items="['tcp', 'udp', 'icmp']"
            label="Protocol"
            variant="outlined"
            class="mb-4"
            :error-messages="form.errors.protocol"
          />
          <VTextField
            v-if="form.protocol !== 'icmp'"
            v-model="form.port"
            label="Port (e.g., 80 or 80-443)"
            variant="outlined"
            class="mb-4"
            :error-messages="form.errors.port"
          />
          <VTextField
            v-model="form.source"
            label="Source IP / CIDR"
            variant="outlined"
            class="mb-4"
            placeholder="0.0.0.0/0"
            :error-messages="form.errors.source"
          />
          <VSelect
            v-model="form.action"
            :items="[
              { title: 'Accept', value: 'accept' },
              { title: 'Drop', value: 'drop' },
              { title: 'Reject', value: 'reject' },
            ]"
            label="Action"
            variant="outlined"
            :error-messages="form.errors.action"
          />
        </VCardText>
        <VCardActions>
          <VSpacer />
          <VBtn variant="text" @click="showAddDialog = false">Cancel</VBtn>
          <VBtn
            color="primary"
            :loading="form.processing"
            @click="submitRule"
          >
            Add Rule
          </VBtn>
        </VCardActions>
      </VCard>
    </VDialog>
  </ServiceTabLayout>
</template>
