<template>
  <div class="space-y-6">
    <div class="flex items-center gap-4">
      <GlassButton @click="$router.back()" class="!px-3 !py-2">
        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18" />
        </svg>
      </GlassButton>
      <h1 class="text-3xl font-bold text-white">Webhook Management</h1>
    </div>
    <p class="text-white/70">Server ID: {{ $route.params.id }}</p>
    
    <!-- Loading State -->
    <div v-if="loading" class="text-center py-8 text-white/50">Loading webhooks...</div>

    <!-- Error State -->
    <div v-else-if="error" class="p-4 bg-red-500/20 border border-red-500/50 rounded-lg text-red-400">
      {{ error }}
    </div>

    <GlassCard v-else class="p-6">
      <WebhookList
        :webhooks="webhooks"
        @add="showAddForm"
        @edit="showEditForm"
        @delete="deleteWebhook"
      />
    </GlassCard>

    <!-- Add/Edit Form Modal -->
    <Teleport to="body">
      <Transition name="modal">
        <div
          v-if="showForm"
          class="fixed inset-0 bg-black/70 backdrop-blur-sm flex items-center justify-center p-4 z-50"
          @click.self="closeForm"
        >
          <div class="bg-gradient-to-br from-gray-900/90 to-gray-800/90 backdrop-blur-xl rounded-2xl p-6 border border-white/20 w-full max-w-2xl max-h-[90vh] overflow-y-auto">
            <div class="flex justify-between items-center mb-4">
              <h2 class="text-xl font-semibold text-cyan-400">
                {{ editingWebhook ? 'Edit Webhook' : 'Add New Webhook' }}
              </h2>
              <button
                @click="closeForm"
                class="p-2 text-white/70 hover:text-white hover:bg-white/10 rounded-lg transition-colors"
              >
                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>
            <WebhookForm
              :webhook="editingWebhook"
              :submit-label="editingWebhook ? 'Update Webhook' : 'Create Webhook'"
              :show-cancel="true"
              @submit="saveWebhook"
              @cancel="closeForm"
            />
          </div>
        </div>
      </Transition>
    </Teleport>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import GlassCard from '../components/glass/GlassCard.vue'
import GlassButton from '../components/glass/GlassButton.vue'
import WebhookList from '../components/WebhookList.vue'
import WebhookForm from '../components/WebhookForm.vue'
import type { Webhook } from '../types/webhook'

const route = useRoute()
const webhooks = ref<Webhook[]>([])
const showForm = ref(false)
const editingWebhook = ref<Webhook | undefined>(undefined)
const loading = ref(true)
const error = ref<string | null>(null)

const fetchWebhooks = async () => {
  loading.value = true
  error.value = null
  try {
    const serverId = route.params.id as string
    const response = await fetch(`/api/servers/${serverId}/webhooks`)
    if (!response.ok) throw new Error('Failed to fetch webhooks')
    webhooks.value = await response.json()
  } catch (err) {
    error.value = err instanceof Error ? err.message : 'An error occurred'
    console.error('Fetch webhooks error:', err)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchWebhooks()
})

const showAddForm = () => {
  editingWebhook.value = undefined
  showForm.value = true
}

const showEditForm = (webhook: Webhook) => {
  editingWebhook.value = webhook
  showForm.value = true
}

const closeForm = () => {
  showForm.value = false
  editingWebhook.value = undefined
}

const saveWebhook = async (webhookData: Omit<Webhook, 'id' | 'createdAt' | 'updatedAt'>) => {
  try {
    const serverId = route.params.id as string
    if (editingWebhook.value) {
      const response = await fetch(`/api/webhooks/${editingWebhook.value.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(webhookData)
      })
      if (!response.ok) throw new Error('Failed to update webhook')
    } else {
      const response = await fetch(`/api/servers/${serverId}/webhooks`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(webhookData)
      })
      if (!response.ok) throw new Error('Failed to create webhook')
    }
    closeForm()
    await fetchWebhooks()
  } catch (err) {
    console.error('Save webhook error:', err)
    alert('Failed to save webhook. Check console for details.')
  }
}

const deleteWebhook = async (id: string) => {
  if (!confirm('Are you sure you want to delete this webhook?')) return
  try {
    const response = await fetch(`/api/webhooks/${id}`, { method: 'DELETE' })
    if (!response.ok) throw new Error('Failed to delete webhook')
    await fetchWebhooks()
  } catch (err) {
    console.error('Delete webhook error:', err)
    alert('Failed to delete webhook. Check console for details.')
  }
}
</script>

<style scoped>
.modal-enter-active,
.modal-leave-active {
  transition: opacity 0.3s ease;
}
.modal-enter-from,
.modal-leave-to {
  opacity: 0;
}
</style>
