<template>
  <AdminLayout title="Postfix (SMTP) Konfigürasyon">
    <Head title="Postfix (SMTP) Konfigürasyon" />

    <!-- Page Header -->
    <div class="mb-6 flex items-center justify-between">
      <div>
        <h1 class="text-2xl font-bold text-slate-900">Postfix SMTP Sunucusu</h1>
        <p class="mt-1 text-sm text-slate-500">
          Postfix global ayarları — demo: DB + UI. Mail servisi kurulduğunda /etc/postfix/main.cf yazımı aktif olur.
        </p>
      </div>
      <span class="inline-flex items-center rounded-full bg-amber-100 px-3 py-1 text-xs font-semibold text-amber-800">
        Hazırlık
      </span>
    </div>

    <!-- Flash Messages -->
    <div v-if="$page.props.flash?.success" class="mb-4 flex items-center gap-2 rounded-lg border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-800">
      <CheckCircleIcon class="h-5 w-5 flex-shrink-0 text-emerald-500" />
      {{ $page.props.flash.success }}
    </div>
    <div v-if="$page.props.flash?.error" class="mb-4 flex items-center gap-2 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-800">
      <ExclamationTriangleIcon class="h-5 w-5 flex-shrink-0 text-red-500" />
      {{ $page.props.flash.error }}
    </div>

    <!-- Tab Navigation -->
    <div class="mb-6 border-b border-slate-200">
      <nav class="-mb-px flex gap-6">
        <button
          v-for="tab in tabs"
          :key="tab.id"
          @click="activeTab = tab.id"
          :class="[
            'flex items-center gap-2 border-b-2 px-1 pb-3 text-sm font-medium transition-colors',
            activeTab === tab.id
              ? 'border-blue-600 text-blue-600'
              : 'border-transparent text-slate-500 hover:border-slate-300 hover:text-slate-700'
          ]"
        >
          <component :is="tab.icon" class="h-4 w-4" />
          {{ tab.label }}
          <span
            v-if="tab.id === 'queue' && status.queue_size > 0"
            class="inline-flex items-center rounded-full bg-blue-100 px-2 py-0.5 text-xs font-semibold text-blue-700"
          >
            {{ status.queue_size }}
          </span>
        </button>
      </nav>
    </div>

    <!-- ═══════════════════════════════════════════════════════════════════════ -->
    <!-- TAB 1: GENEL BAKIŞ -->
    <!-- ═══════════════════════════════════════════════════════════════════════ -->
    <div v-if="activeTab === 'overview'">

      <!-- Status + Version Card -->
      <div class="mb-6 rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
        <div class="flex flex-wrap items-start justify-between gap-4">
          <div class="flex items-center gap-4">
            <div class="flex h-12 w-12 items-center justify-center rounded-xl bg-blue-50">
              <EnvelopeIcon class="h-6 w-6 text-blue-600" />
            </div>
            <div>
              <div class="flex items-center gap-2">
                <h2 class="text-lg font-semibold text-slate-900">Postfix SMTP</h2>
                <span :class="serviceBadgeClass">
                  <span class="mr-1.5 inline-block h-2 w-2 rounded-full" :class="status.service === 'active' ? 'bg-emerald-500' : 'bg-red-500'"></span>
                  {{ status.service === 'active' ? 'Çalışıyor' : 'Durduruldu' }}
                </span>
              </div>
              <p class="mt-0.5 text-sm text-slate-500">
                {{ status.mail_version }} &bull; PID: <code class="font-mono text-xs text-slate-700">{{ status.pid }}</code>
              </p>
            </div>
          </div>
          <div class="flex items-center gap-2 text-sm text-slate-500">
            <ClockIcon class="h-4 w-4" />
            Uptime: {{ status.uptime }}
          </div>
        </div>
      </div>

      <!-- Queue Stats -->
      <div class="mb-6 grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-5">
        <div v-for="stat in queueStats" :key="stat.label" class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
          <p class="text-xs font-medium uppercase tracking-wide text-slate-500">{{ stat.label }}</p>
          <p class="mt-1 text-2xl font-bold" :class="stat.colorClass">{{ stat.value }}</p>
        </div>
      </div>

      <!-- Action Buttons -->
      <div class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
        <h3 class="mb-4 text-sm font-semibold text-slate-700">Servis İşlemleri</h3>
        <div class="flex flex-wrap gap-3">
          <button @click="doAction('test')" :disabled="actionLoading" class="btn-action btn-slate">
            <ShieldCheckIcon class="h-4 w-4" />
            Test Config
          </button>
          <button @click="doAction('reload')" :disabled="actionLoading" class="btn-action btn-blue">
            <ArrowPathIcon class="h-4 w-4" />
            Reload
          </button>
          <button @click="doAction('restart')" :disabled="actionLoading" class="btn-action btn-amber">
            <BoltIcon class="h-4 w-4" />
            Restart
          </button>
          <button @click="doAction('flush')" :disabled="actionLoading" class="btn-action btn-indigo">
            <ArrowUturnLeftIcon class="h-4 w-4" />
            Flush Queue
          </button>
          <a :href="route('admin.mail.postfix.export')" class="btn-action btn-slate">
            <ArrowDownTrayIcon class="h-4 w-4" />
            Export main.cf
          </a>
        </div>
      </div>
    </div>

    <!-- ═══════════════════════════════════════════════════════════════════════ -->
    <!-- TAB 2: KONFİGÜRASYON -->
    <!-- ═══════════════════════════════════════════════════════════════════════ -->
    <div v-if="activeTab === 'config'">
      <form @submit.prevent="submitConfig">
        <div v-for="(rows, category) in grouped" :key="category" class="mb-6 rounded-xl border border-slate-200 bg-white shadow-sm">
          <!-- Category Header -->
          <div class="flex items-center gap-3 border-b border-slate-100 px-5 py-4">
            <component :is="categoryIcon(category)" class="h-5 w-5 text-slate-400" />
            <h3 class="font-semibold text-slate-800">{{ categoryLabel(category) }}</h3>
            <span class="ml-auto rounded-full bg-slate-100 px-2.5 py-0.5 text-xs text-slate-500">
              {{ rows.length }} parametre
            </span>
          </div>

          <!-- Config Rows -->
          <div class="divide-y divide-slate-50">
            <div
              v-for="row in rows"
              :key="row.key"
              class="grid grid-cols-1 gap-3 px-5 py-4 lg:grid-cols-[280px_1fr_auto]"
            >
              <!-- Key + Description -->
              <div>
                <code class="font-mono text-sm font-semibold text-slate-800">{{ row.key }}</code>
                <p v-if="row.description_tr" class="mt-0.5 text-xs text-slate-500">{{ row.description_tr }}</p>
                <p class="mt-0.5 text-xs text-slate-400">
                  <span class="rounded bg-slate-100 px-1.5 py-0.5 font-mono text-[11px]">{{ row.data_type }}</span>
                  <span class="ml-1 text-slate-300">default:</span>
                  <code class="ml-1 font-mono text-[11px] text-slate-400">{{ row.default_value || '(boş)' }}</code>
                </p>
              </div>

              <!-- Input -->
              <div>
                <!-- Boolean toggle -->
                <template v-if="row.data_type === 'boolean'">
                  <label class="relative inline-flex cursor-pointer items-center gap-3">
                    <input
                      type="checkbox"
                      :checked="configForm.settings[row.key] === '1' || configForm.settings[row.key] === 'yes'"
                      @change="(e) => configForm.settings[row.key] = (e.target as HTMLInputElement).checked ? '1' : '0'"
                      class="sr-only"
                    />
                    <div
                      :class="[
                        'relative h-6 w-11 rounded-full transition-colors',
                        (configForm.settings[row.key] === '1' || configForm.settings[row.key] === 'yes') ? 'bg-blue-600' : 'bg-slate-200'
                      ]"
                    >
                      <span
                        :class="[
                          'absolute top-0.5 left-0.5 h-5 w-5 rounded-full bg-white shadow transition-transform',
                          (configForm.settings[row.key] === '1' || configForm.settings[row.key] === 'yes') ? 'translate-x-5' : 'translate-x-0'
                        ]"
                      ></span>
                    </div>
                    <span class="text-sm text-slate-700">
                      {{ (configForm.settings[row.key] === '1' || configForm.settings[row.key] === 'yes') ? 'Aktif' : 'Pasif' }}
                    </span>
                  </label>
                </template>

                <!-- Enum select -->
                <template v-else-if="row.data_type === 'enum' && row.enum_values">
                  <select
                    v-model="configForm.settings[row.key]"
                    class="input-field"
                  >
                    <option v-for="opt in row.enum_values" :key="opt" :value="opt">{{ opt }}</option>
                  </select>
                </template>

                <!-- Integer -->
                <template v-else-if="row.data_type === 'integer'">
                  <input
                    type="number"
                    v-model="configForm.settings[row.key]"
                    class="input-field"
                    min="0"
                  />
                </template>

                <!-- Bytes (monospace text) -->
                <template v-else-if="row.data_type === 'bytes'">
                  <div class="flex items-center gap-2">
                    <input
                      type="text"
                      v-model="configForm.settings[row.key]"
                      class="input-field font-mono"
                    />
                    <span class="text-xs text-slate-400">
                      {{ formatBytes(Number(configForm.settings[row.key])) }}
                    </span>
                  </div>
                </template>

                <!-- Default: text string -->
                <template v-else>
                  <input
                    type="text"
                    v-model="configForm.settings[row.key]"
                    :class="[
                      'input-field',
                      isMonospaceKey(row.key) ? 'font-mono text-sm' : ''
                    ]"
                  />
                </template>
              </div>

              <!-- Reset button -->
              <div class="flex items-start">
                <button
                  type="button"
                  @click="resetRow(row)"
                  class="flex items-center gap-1 rounded-lg px-2.5 py-1.5 text-xs text-slate-400 hover:bg-slate-100 hover:text-slate-600"
                  title="Varsayılana sıfırla"
                >
                  <ArrowUturnLeftIcon class="h-3.5 w-3.5" />
                  Varsayılan
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- Sticky Save Bar -->
        <div class="sticky bottom-0 z-10 -mx-0 flex items-center justify-between rounded-xl border border-slate-200 bg-white px-5 py-4 shadow-lg">
          <div class="flex items-center gap-2 text-sm text-slate-500">
            <InformationCircleIcon class="h-4 w-4 text-amber-500" />
            Kaydedilen değerler mail servisi kurulduğunda /etc/postfix/main.cf'e yazılır ve reload gerekir.
          </div>
          <div class="flex gap-3">
            <button
              type="button"
              @click="doAction('reset')"
              class="btn-action btn-slate"
            >
              <ArrowUturnLeftIcon class="h-4 w-4" />
              Tümünü Varsayılana Sıfırla
            </button>
            <button
              type="submit"
              :disabled="configForm.processing"
              class="btn-action btn-blue"
            >
              <CheckCircleIcon class="h-4 w-4" />
              {{ configForm.processing ? 'Kaydediliyor...' : 'Tümünü Kaydet' }}
            </button>
          </div>
        </div>
      </form>
    </div>

    <!-- ═══════════════════════════════════════════════════════════════════════ -->
    <!-- TAB 3: MAIL KUYRUĞu -->
    <!-- ═══════════════════════════════════════════════════════════════════════ -->
    <div v-if="activeTab === 'queue'">
      <div class="mb-4 flex items-center justify-between">
        <h3 class="text-sm font-semibold text-slate-700">Mail Kuyruğu (mailq)</h3>
        <button @click="doAction('flush')" class="btn-action btn-indigo">
          <ArrowUturnLeftIcon class="h-4 w-4" />
          Flush Queue
        </button>
      </div>

      <div class="rounded-xl border border-slate-200 bg-white shadow-sm">
        <div class="overflow-x-auto">
          <table class="min-w-full divide-y divide-slate-100 text-sm">
            <thead class="bg-slate-50">
              <tr>
                <th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">Queue ID</th>
                <th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">Boyut</th>
                <th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">Geliş Zamanı</th>
                <th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">Gönderici</th>
                <th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">Alıcı(lar)</th>
                <th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">Durum</th>
                <th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">İşlem</th>
              </tr>
            </thead>
            <tbody class="divide-y divide-slate-50">
              <tr v-for="entry in queue" :key="entry.queue_id" class="hover:bg-slate-50">
                <td class="px-4 py-3">
                  <code class="font-mono text-xs font-semibold text-slate-700">{{ entry.queue_id }}</code>
                </td>
                <td class="px-4 py-3 text-slate-600">{{ entry.size_kb }} KB</td>
                <td class="px-4 py-3 text-slate-500 text-xs">{{ entry.arrival_time }}</td>
                <td class="px-4 py-3">
                  <code class="font-mono text-xs text-slate-700">{{ entry.sender }}</code>
                </td>
                <td class="px-4 py-3">
                  <div class="max-w-[200px]">
                    <code class="font-mono text-xs text-slate-600">{{ entry.recipients[0] }}</code>
                    <span v-if="entry.recipients.length > 1" class="ml-1 text-xs text-slate-400">+{{ entry.recipients.length - 1 }}</span>
                  </div>
                  <p v-if="entry.reason" class="mt-0.5 text-xs text-red-500">{{ entry.reason }}</p>
                </td>
                <td class="px-4 py-3">
                  <span :class="queueStatusBadge(entry.status)">
                    {{ queueStatusLabel(entry.status) }}
                  </span>
                </td>
                <td class="px-4 py-3">
                  <button
                    @click="deleteQueueItem(entry.queue_id)"
                    class="flex items-center gap-1 rounded px-2 py-1 text-xs text-red-500 hover:bg-red-50 hover:text-red-700"
                    title="Sil (postsuper -d)"
                  >
                    <TrashIcon class="h-3.5 w-3.5" />
                    Sil
                  </button>
                </td>
              </tr>

              <tr v-if="queue.length === 0">
                <td colspan="7" class="px-4 py-10 text-center text-sm text-slate-400">
                  Kuyruk boş.
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

  </AdminLayout>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { Head } from '@inertiajs/vue3'
import { useForm, router } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import {
  EnvelopeIcon,
  Cog6ToothIcon,
  BoltIcon,
  ArrowPathIcon,
  PlayIcon,
  ArrowDownTrayIcon,
  ArrowUturnLeftIcon,
  ServerIcon,
  ClockIcon,
  CheckCircleIcon,
  ExclamationTriangleIcon,
  TrashIcon,
  InformationCircleIcon,
  ShieldCheckIcon,
  LockClosedIcon,
} from '@heroicons/vue/24/outline'
import { useConfirm } from '@/composables/useConfirm'

const { ask } = useConfirm()

// ─── Props ───────────────────────────────────────────────────────────────────

interface ConfigRow {
  id: number
  key: string
  value: string | null
  default_value: string | null
  category: string
  data_type: string
  enum_values: string[] | null
  description_tr: string | null
}

interface QueueEntry {
  queue_id: string
  size_kb: number
  arrival_time: string
  sender: string
  recipients: string[]
  status: 'active' | 'deferred' | 'hold' | 'corrupt'
  reason: string | null
}

const props = defineProps<{
  grouped: Record<string, ConfigRow[]>
  status: {
    service: string
    pid: number
    uptime: string
    queue_size: number
    deferred: number
    hold: number
    corrupt: number
    mail_version: string
  }
  queue: QueueEntry[]
}>()

// ─── Tabs ────────────────────────────────────────────────────────────────────

const activeTab = ref<'overview' | 'config' | 'queue'>('overview')
const actionLoading = ref(false)

const tabs = [
  { id: 'overview', label: 'Genel Bakış',   icon: ServerIcon },
  { id: 'config',   label: 'Konfigürasyon', icon: Cog6ToothIcon },
  { id: 'queue',    label: 'Mail Kuyruğu',  icon: EnvelopeIcon },
] as const

// ─── Service badge ────────────────────────────────────────────────────────────

const serviceBadgeClass = computed(() =>
  props.status.service === 'active'
    ? 'inline-flex items-center rounded-full bg-emerald-100 px-2.5 py-0.5 text-xs font-semibold text-emerald-800'
    : 'inline-flex items-center rounded-full bg-red-100 px-2.5 py-0.5 text-xs font-semibold text-red-800'
)

// ─── Queue stats ──────────────────────────────────────────────────────────────

const queueStats = computed(() => [
  { label: 'Toplam',   value: props.status.queue_size, colorClass: 'text-slate-800' },
  { label: 'Aktif',    value: props.queue.filter(q => q.status === 'active').length,   colorClass: 'text-blue-600' },
  { label: 'Deferred', value: props.status.deferred, colorClass: 'text-amber-600' },
  { label: 'Hold',     value: props.status.hold,     colorClass: 'text-slate-500' },
  { label: 'Corrupt',  value: props.status.corrupt,  colorClass: 'text-red-600' },
])

// ─── Config form ──────────────────────────────────────────────────────────────

const initialSettings = Object.fromEntries(
  Object.values(props.grouped)
    .flat()
    .map(row => [row.key, row.value ?? ''])
)

const configForm = useForm({
  settings: { ...initialSettings },
})

const submitConfig = () => {
  configForm.patch(route('admin.mail.postfix.update'))
}

const resetRow = (row: ConfigRow) => {
  configForm.settings[row.key] = row.default_value ?? ''
}

// ─── Category meta ────────────────────────────────────────────────────────────

const categoryLabels: Record<string, string> = {
  general:    'Genel',
  networking: 'Ağ',
  limits:     'Limitler',
  security:   'Güvenlik',
  queue:      'Kuyruk',
  virtual:    'Virtual Hosting (MySQL)',
}

const categoryIcons: Record<string, unknown> = {
  general:    Cog6ToothIcon,
  networking: ServerIcon,
  limits:     InformationCircleIcon,
  security:   LockClosedIcon,
  queue:      ClockIcon,
  virtual:    EnvelopeIcon,
}

const categoryLabel = (cat: string) => categoryLabels[cat] ?? cat
const categoryIcon  = (cat: string) => categoryIcons[cat] ?? Cog6ToothIcon

// ─── Helpers ─────────────────────────────────────────────────────────────────

const isMonospaceKey = (key: string): boolean =>
  ['myhostname', 'mydomain', 'myorigin', 'mydestination', 'mynetworks',
   'queue_directory', 'smtpd_tls_cert_file', 'smtpd_tls_key_file',
   'virtual_mailbox_domains', 'virtual_mailbox_maps', 'virtual_alias_maps',
   'smtpd_relay_restrictions', 'smtpd_sender_restrictions', 'smtpd_recipient_restrictions',
   'smtpd_banner'].includes(key)

const formatBytes = (bytes: number): string => {
  if (!bytes || isNaN(bytes)) return ''
  if (bytes === 0) return '0 = Sınırsız'
  const units = ['B', 'KB', 'MB', 'GB']
  let i = 0
  let val = bytes
  while (val >= 1024 && i < units.length - 1) {
    val /= 1024
    i++
  }
  return `≈ ${val.toFixed(1)} ${units[i]}`
}

const queueStatusBadge = (status: string): string => {
  const map: Record<string, string> = {
    active:   'inline-flex items-center rounded-full bg-blue-100 px-2 py-0.5 text-xs font-semibold text-blue-700',
    deferred: 'inline-flex items-center rounded-full bg-amber-100 px-2 py-0.5 text-xs font-semibold text-amber-700',
    hold:     'inline-flex items-center rounded-full bg-slate-100 px-2 py-0.5 text-xs font-semibold text-slate-600',
    corrupt:  'inline-flex items-center rounded-full bg-red-100 px-2 py-0.5 text-xs font-semibold text-red-700',
  }
  return map[status] ?? map.hold
}

const queueStatusLabel = (status: string): string => {
  const map: Record<string, string> = {
    active:   'Aktif',
    deferred: 'Ertelenmiş',
    hold:     'Hold',
    corrupt:  'Bozuk',
  }
  return map[status] ?? status
}

// ─── Actions ─────────────────────────────────────────────────────────────────

const doAction = async (action: string) => {
  const routes: Record<string, string> = {
    reload:  route('admin.mail.postfix.reload'),
    restart: route('admin.mail.postfix.restart'),
    test:    route('admin.mail.postfix.test'),
    flush:   route('admin.mail.postfix.queue.flush'),
    reset:   route('admin.mail.postfix.reset'),
  }

  const url = routes[action]
  if (!url) return

  actionLoading.value = true

  if (action === 'reset') {
    const ok = await ask({
      title: 'Postfix ayarlarını sıfırla',
      message: 'Tüm Postfix ayarları varsayılan değerlere döndürülecek. Mevcut özelleştirmeler kaybolur.',
      variant: 'danger',
      confirmText: 'Sıfırla',
      cancelText: 'İptal',
    })
    if (!ok) {
      actionLoading.value = false
      return
    }
  }

  router.post(url, {}, {
    onFinish: () => { actionLoading.value = false },
  })
}

const deleteQueueItem = async (queueId: string) => {
  const ok = await ask({
      title: 'Onaylayın',
      message: `"${queueId}" kuyruktan silinecek. Devam etmek istiyor musunuz?`,
      variant: 'danger',
      confirmText: 'Sil',
      cancelText: 'İptal',
  })
  if (!ok) return
  router.delete(route('admin.mail.postfix.queue.delete', { queueId }))
}
</script>

<style scoped>
.btn-action {
  @apply inline-flex items-center gap-1.5 rounded-lg px-3 py-2 text-sm font-medium transition-colors disabled:opacity-50;
}
.btn-blue  { @apply bg-blue-600 text-white hover:bg-blue-700; }
.btn-slate { @apply border border-slate-200 bg-white text-slate-700 hover:bg-slate-50; }
.btn-amber { @apply bg-amber-500 text-white hover:bg-amber-600; }
.btn-indigo{ @apply bg-indigo-600 text-white hover:bg-indigo-700; }

.input-field {
  @apply block w-full rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm text-slate-900 focus:border-blue-400 focus:outline-none focus:ring-2 focus:ring-blue-100;
}
</style>
