<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { useAppStore } from '@/stores/app'
import { opsAPI } from '@/api/admin/ops'
import type { WebhookNotificationConfig, AlertSeverity } from '@/api/admin/ops'
import BaseDialog from '@/components/common/BaseDialog.vue'
import Select from '@/components/common/Select.vue'

const { t } = useI18n()
const appStore = useAppStore()

const loading = ref(false)
const config = ref<WebhookNotificationConfig | null>(null)

const showEditor = ref(false)
const saving = ref(false)
const draft = ref<WebhookNotificationConfig | null>(null)
const alertUrlInput = ref('')
const reportUrlInput = ref('')

const severityOptions: Array<{ value: AlertSeverity | ''; label: string }> = [
  { value: '', label: t('admin.ops.webhookNotification.minSeverityAll') },
  { value: 'critical', label: t('common.critical') },
  { value: 'warning', label: t('common.warning') },
  { value: 'info', label: t('common.info') }
]

async function loadConfig() {
  loading.value = true
  try {
    const data = await opsAPI.getWebhookNotificationConfig()
    config.value = data
  } catch (err: any) {
    console.error('[OpsWebhookNotificationCard] Failed to load config', err)
    appStore.showError(err?.response?.data?.detail || t('admin.ops.webhookNotification.loadFailed'))
  } finally {
    loading.value = false
  }
}

async function saveConfig() {
  if (!draft.value) return
  if (!editorValidation.value.valid) {
    appStore.showError(editorValidation.value.errors[0] || t('admin.ops.webhookNotification.validation.invalid'))
    return
  }
  saving.value = true
  try {
    config.value = await opsAPI.updateWebhookNotificationConfig(draft.value)
    showEditor.value = false
    appStore.showSuccess(t('admin.ops.webhookNotification.saveSuccess'))
  } catch (err: any) {
    console.error('[OpsWebhookNotificationCard] Failed to save config', err)
    appStore.showError(err?.response?.data?.detail || t('admin.ops.webhookNotification.saveFailed'))
  } finally {
    saving.value = false
  }
}

function openEditor() {
  if (!config.value) return
  draft.value = JSON.parse(JSON.stringify(config.value))
  alertUrlInput.value = ''
  reportUrlInput.value = ''
  showEditor.value = true
}

function isValidUrl(url: string): boolean {
  try {
    new URL(url)
    return url.startsWith('http://') || url.startsWith('https://')
  } catch {
    return false
  }
}

function addAlertUrl() {
  if (!draft.value) return
  const url = alertUrlInput.value.trim()
  if (url && isValidUrl(url)) {
    if (!draft.value.alert.urls.includes(url)) {
      draft.value.alert.urls.push(url)
    }
    alertUrlInput.value = ''
  }
}

function removeAlertUrl(index: number) {
  if (!draft.value) return
  draft.value.alert.urls.splice(index, 1)
}

function addReportUrl() {
  if (!draft.value) return
  const url = reportUrlInput.value.trim()
  if (url && isValidUrl(url)) {
    if (!draft.value.report.urls.includes(url)) {
      draft.value.report.urls.push(url)
    }
    reportUrlInput.value = ''
  }
}

function removeReportUrl(index: number) {
  if (!draft.value) return
  draft.value.report.urls.splice(index, 1)
}

const editorValidation = computed(() => {
  const errors: string[] = []
  if (!draft.value) return { valid: true, errors }

  if (draft.value.alert.enabled && draft.value.alert.urls.length === 0) {
    errors.push(t('admin.ops.webhookNotification.validation.urlsRequired'))
  }
  if (draft.value.report.enabled && draft.value.report.urls.length === 0) {
    errors.push(t('admin.ops.webhookNotification.validation.urlsRequired'))
  }

  const invalidAlertUrls = draft.value.alert.urls.filter((u) => !isValidUrl(u))
  if (invalidAlertUrls.length > 0) errors.push(t('admin.ops.webhookNotification.validation.invalidUrls'))

  const invalidReportUrls = draft.value.report.urls.filter((u) => !isValidUrl(u))
  if (invalidReportUrls.length > 0) errors.push(t('admin.ops.webhookNotification.validation.invalidUrls'))

  if (draft.value.alert.timeout_seconds < 1 || draft.value.alert.timeout_seconds > 60) {
    errors.push(t('admin.ops.webhookNotification.validation.timeoutRange'))
  }
  if (draft.value.alert.rate_limit_per_hour < 0) {
    errors.push(t('admin.ops.webhookNotification.validation.rateLimitRange'))
  }

  return { valid: errors.length === 0, errors }
})

onMounted(loadConfig)
</script>

<template>
  <div class="rounded-lg border border-gray-200 bg-white p-4 dark:border-gray-700 dark:bg-gray-800">
    <div class="mb-4 flex items-center justify-between">
      <div>
        <h3 class="text-lg font-semibold text-gray-900 dark:text-gray-100">
          {{ t('admin.ops.webhookNotification.title') }}
        </h3>
        <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">
          {{ t('admin.ops.webhookNotification.description') }}
        </p>
      </div>
      <button
        class="btn btn-secondary text-sm"
        @click="openEditor"
        :disabled="loading || !config"
      >
        {{ t('common.edit') }}
      </button>
    </div>

    <div v-if="loading" class="py-8 text-center text-gray-500">
      {{ t('admin.ops.webhookNotification.loading') }}
    </div>

    <div v-else-if="config" class="space-y-4">
      <!-- Alert Webhook Status -->
      <div class="flex items-center justify-between border-b border-gray-100 pb-3 dark:border-gray-700">
        <span class="font-medium text-gray-700 dark:text-gray-300">{{ t('admin.ops.webhookNotification.alertTitle') }}</span>
        <span
          :class="config.alert.enabled && config.alert.urls.length > 0
            ? 'text-green-600 dark:text-green-400'
            : 'text-gray-400'"
          class="text-sm"
        >
          {{ config.alert.enabled && config.alert.urls.length > 0 ? t('common.enabled') : t('common.disabled') }}
        </span>
      </div>

      <div v-if="config.alert.enabled && config.alert.urls.length > 0" class="text-sm text-gray-600 dark:text-gray-400">
        <div class="mb-1">{{ config.alert.urls.length }} webhook(s) configured</div>
        <div class="text-xs">Min severity: {{ config.alert.min_severity || 'all' }}</div>
      </div>

      <!-- Report Webhook Status -->
      <div class="flex items-center justify-between border-b border-gray-100 pb-3 dark:border-gray-700">
        <span class="font-medium text-gray-700 dark:text-gray-300">{{ t('admin.ops.webhookNotification.reportTitle') }}</span>
        <span
          :class="config.report.enabled && config.report.urls.length > 0
            ? 'text-green-600 dark:text-green-400'
            : 'text-gray-400'"
          class="text-sm"
        >
          {{ config.report.enabled && config.report.urls.length > 0 ? t('common.enabled') : t('common.disabled') }}
        </span>
      </div>
    </div>
  </div>

  <!-- Editor Dialog -->
  <BaseDialog
    :show="showEditor"
    :title="t('admin.ops.webhookNotification.title')"
    width="wide"
    @close="showEditor = false"
  >
    <div v-if="draft" class="space-y-6">
      <!-- Alert Webhooks -->
      <div>
        <h4 class="mb-3 font-medium text-gray-900 dark:text-gray-100">
          {{ t('admin.ops.webhookNotification.alertTitle') }}
        </h4>
        <div class="space-y-3">
          <label class="inline-flex items-center gap-2">
            <input v-model="draft.alert.enabled" type="checkbox" class="checkbox" />
            <span class="text-sm">{{ t('common.enable') }}</span>
          </label>

          <div v-if="draft.alert.enabled">
            <label class="mb-1 block text-xs font-medium text-gray-600 dark:text-gray-400">
              {{ t('admin.ops.webhookNotification.urls') }}
            </label>
            <div class="flex gap-2">
              <input
                v-model="alertUrlInput"
                type="url"
                class="input flex-1"
                :placeholder="'https://example.com/webhook'"
                @keyup.enter="addAlertUrl"
              />
              <button type="button" class="btn btn-secondary" @click="addAlertUrl">
                {{ t('common.add') }}
              </button>
            </div>
            <div v-if="draft.alert.urls.length > 0" class="mt-2 space-y-1">
              <div
                v-for="(url, index) in draft.alert.urls"
                :key="index"
                class="flex items-center justify-between rounded bg-gray-50 px-2 py-1 text-sm dark:bg-gray-700"
              >
                <span class="truncate text-gray-700 dark:text-gray-300">{{ url }}</span>
                <button
                  type="button"
                  class="text-gray-400 hover:text-red-500"
                  @click="removeAlertUrl(index)"
                >
                  ×
                </button>
              </div>
            </div>
          </div>

          <div v-if="draft.alert.enabled" class="grid grid-cols-2 gap-4">
            <div>
              <label class="mb-1 block text-xs font-medium text-gray-600 dark:text-gray-400">
                {{ t('admin.ops.webhookNotification.minSeverity') }}
              </label>
              <Select
                v-model="draft.alert.min_severity"
                :options="severityOptions"
                class="w-full"
              />
            </div>
            <div>
              <label class="mb-1 block text-xs font-medium text-gray-600 dark:text-gray-400">
                {{ t('admin.ops.webhookNotification.timeoutSeconds') }}
              </label>
              <input v-model.number="draft.alert.timeout_seconds" type="number" min="1" max="60" class="input w-full" />
            </div>
          </div>

          <div v-if="draft.alert.enabled" class="grid grid-cols-2 gap-4">
            <div>
              <label class="mb-1 block text-xs font-medium text-gray-600 dark:text-gray-400">
                {{ t('admin.ops.webhookNotification.rateLimitPerHour') }}
              </label>
              <input v-model.number="draft.alert.rate_limit_per_hour" type="number" min="0" class="input w-full" />
            </div>
            <label class="inline-flex items-center gap-2">
              <input v-model="draft.alert.include_resolved" type="checkbox" class="checkbox" />
              <span class="text-sm">{{ t('admin.ops.webhookNotification.includeResolved') }}</span>
            </label>
          </div>

          <div v-if="draft.alert.enabled">
            <label class="mb-1 block text-xs font-medium text-gray-600 dark:text-gray-400">
              {{ t('admin.ops.webhookNotification.secret') }}
            </label>
            <input
              v-model="draft.alert.secret"
              type="password"
              class="input w-full"
              :placeholder="t('admin.ops.webhookNotification.secretHint')"
            />
          </div>
        </div>
      </div>

      <!-- Report Webhooks -->
      <div>
        <h4 class="mb-3 font-medium text-gray-900 dark:text-gray-100">
          {{ t('admin.ops.webhookNotification.reportTitle') }}
        </h4>
        <div class="space-y-3">
          <label class="inline-flex items-center gap-2">
            <input v-model="draft.report.enabled" type="checkbox" class="checkbox" />
            <span class="text-sm">{{ t('common.enable') }}</span>
          </label>

          <div v-if="draft.report.enabled">
            <label class="mb-1 block text-xs font-medium text-gray-600 dark:text-gray-400">
              {{ t('admin.ops.webhookNotification.urls') }}
            </label>
            <div class="flex gap-2">
              <input
                v-model="reportUrlInput"
                type="url"
                class="input flex-1"
                :placeholder="'https://example.com/webhook'"
                @keyup.enter="addReportUrl"
              />
              <button type="button" class="btn btn-secondary" @click="addReportUrl">
                {{ t('common.add') }}
              </button>
            </div>
            <div v-if="draft.report.urls.length > 0" class="mt-2 space-y-1">
              <div
                v-for="(url, index) in draft.report.urls"
                :key="index"
                class="flex items-center justify-between rounded bg-gray-50 px-2 py-1 text-sm dark:bg-gray-700"
              >
                <span class="truncate text-gray-700 dark:text-gray-300">{{ url }}</span>
                <button
                  type="button"
                  class="text-gray-400 hover:text-red-500"
                  @click="removeReportUrl(index)"
                >
                  ×
                </button>
              </div>
            </div>
          </div>

          <div v-if="draft.report.enabled">
            <label class="mb-1 block text-xs font-medium text-gray-600 dark:text-gray-400">
              {{ t('admin.ops.webhookNotification.secret') }}
            </label>
            <input
              v-model="draft.report.secret"
              type="password"
              class="input w-full"
              :placeholder="t('admin.ops.webhookNotification.secretHint')"
            />
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="flex justify-end gap-2">
        <button type="button" class="btn btn-secondary" @click="showEditor = false">
          {{ t('common.cancel') }}
        </button>
        <button
          type="button"
          class="btn btn-primary"
          :disabled="saving || !editorValidation.valid"
          @click="saveConfig"
        >
          {{ saving ? t('common.saving') : t('common.save') }}
        </button>
      </div>
    </template>
  </BaseDialog>
</template>
