<script setup>
import { ref, computed } from 'vue'
import { Head, Link, router } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import {
    LockClosedIcon,
    ShieldCheckIcon,
    ExclamationTriangleIcon,
    ClockIcon,
    ArrowPathIcon,
    CheckCircleIcon,
    XCircleIcon,
    EyeIcon,
    NoSymbolIcon,
    BoltIcon,
    SignalSlashIcon,
} from '@heroicons/vue/24/outline'
import { useConfirm } from '@/composables/useConfirm'

const { ask } = useConfirm()

const props = defineProps({
    certificates:      { type: Array,  required: true },
    stats:             { type: Object, required: true },
    server_rate_limit: { type: Object, required: true },
    filters:           { type: Object, required: true },
})

// ── Filters ───────────────────────────────────────────────────────────
const filterStatus     = ref(props.filters.status ?? '')
const filterExpiring   = ref(props.filters.expiring ?? '')
const filterSearch     = ref(props.filters.search ?? '')
const filterAutoRenew  = ref(
    props.filters.auto_renew === null || props.filters.auto_renew === undefined
        ? ''
        : (props.filters.auto_renew ? '1' : '0')
)

function applyFilters() {
    const params = {}
    if (filterStatus.value)    params.status = filterStatus.value
    if (filterExpiring.value)  params.expiring = filterExpiring.value
    if (filterSearch.value)    params.search = filterSearch.value
    if (filterAutoRenew.value) params.auto_renew = filterAutoRenew.value
    router.get(route('admin.ssl.autossl.index'), params, {
        preserveScroll: true,
        preserveState: true,
        replace: true,
    })
}

function resetFilters() {
    filterStatus.value = ''
    filterExpiring.value = ''
    filterSearch.value = ''
    filterAutoRenew.value = ''
    router.get(route('admin.ssl.autossl.index'), {}, {
        preserveScroll: true,
        preserveState: true,
        replace: true,
    })
}

// ── Bulk selection ────────────────────────────────────────────────────
const selectedIds = ref(new Set())

function toggleSelect(id) {
    const next = new Set(selectedIds.value)
    if (next.has(id)) next.delete(id)
    else next.add(id)
    selectedIds.value = next
}

function toggleSelectAll() {
    if (selectedIds.value.size === props.certificates.length) {
        selectedIds.value = new Set()
    } else {
        selectedIds.value = new Set(props.certificates.map(c => c.id))
    }
}

const allSelected = computed(
    () => props.certificates.length > 0 && selectedIds.value.size === props.certificates.length
)

// ── Actions ───────────────────────────────────────────────────────────
async function forceRenewOne(cert) {
    const ok = await ask({
        title: 'Sertifika Yenileme',
        message: `${cert.domain_name || cert.common_name} icin force renew calistirilsin mi?`,
        variant: 'warning',
        confirmText: 'Yenile',
        cancelText: 'Iptal',
    })
    if (ok) {
        router.post(route('admin.ssl.autossl.force-renew', cert.id), {}, { preserveScroll: true })
    }
}

async function toggleAutoRenew(cert) {
    router.post(
        route('admin.ssl.autossl.toggle-auto-renew', cert.id),
        {},
        { preserveScroll: true }
    )
}

async function checkRblOne(cert) {
    router.post(route('admin.ssl.autossl.check-rbl', cert.id), {}, { preserveScroll: true })
}

async function bulkRenewSelected() {
    if (selectedIds.value.size === 0) return

    const ok = await ask({
        title: 'Toplu Yenileme',
        message: `${selectedIds.value.size} sertifika icin toplu force renew yapilacak. ` +
                 `Rate-limit edilen domain'ler atlanir. Devam etmek icin asagiya "ONAYLA" yaz.`,
        variant: 'danger',
        confirmText: 'Devam',
        cancelText: 'Iptal',
        inputLabel: 'Onay metni',
        inputPlaceholder: 'ONAYLA',
    })
    if (!ok) return

    const confirmation = typeof ok === 'string' ? ok : 'ONAYLA'

    router.post(
        route('admin.ssl.autossl.bulk-renew'),
        {
            cert_ids: Array.from(selectedIds.value),
            confirmation,
        },
        {
            preserveScroll: true,
            onSuccess: () => { selectedIds.value = new Set() },
        }
    )
}

// ── Helpers ───────────────────────────────────────────────────────────
function daysClass(days) {
    if (days === null || days === undefined) return 'text-slate-400'
    if (days < 0) return 'text-slate-500 line-through'
    if (days < 30) return 'text-red-600 font-semibold'
    if (days < 60) return 'text-amber-600 font-semibold'
    return 'text-emerald-600 font-semibold'
}

function daysLabel(days) {
    if (days === null || days === undefined) return '—'
    if (days < 0) return `${Math.abs(days)}g once`
    return `${days}g kaldi`
}

function statusBadge(status) {
    return {
        active:       'bg-emerald-100 text-emerald-800',
        renewing:     'bg-blue-100 text-blue-800',
        pending:      'bg-slate-100 text-slate-700',
        provisioning: 'bg-blue-100 text-blue-800',
        expired:      'bg-red-100 text-red-800',
        error:        'bg-red-200 text-red-900',
    }[status] ?? 'bg-slate-100 text-slate-700'
}

function statusLabel(status) {
    return {
        active: 'Aktif',
        renewing: 'Yenileniyor',
        pending: 'Bekliyor',
        provisioning: 'Alinior',
        expired: 'Suresi Dolmus',
        error: 'Hatali',
    }[status] ?? status ?? '—'
}

function issuerLabel(issuer) {
    return {
        'lets-encrypt': "Let's Encrypt",
        'custom': 'Custom',
        'self-signed': 'Self-Signed',
    }[issuer] ?? issuer ?? '—'
}

function shortDate(iso) {
    if (!iso) return '—'
    return String(iso).slice(0, 10)
}

const capacityPct = computed(() => {
    const orders = props.server_rate_limit.orders_last_hour ?? 0
    return Math.min(100, Math.round((orders / 300) * 100))
})

const capacityBarClass = computed(() => {
    const pct = capacityPct.value
    if (pct >= 90) return 'bg-red-500'
    if (pct >= 70) return 'bg-amber-500'
    return 'bg-emerald-500'
})
</script>

<template>
    <Head title="AutoSSL Manager" />

    <AdminLayout>
        <template #header>Admin AutoSSL Manager</template>

        <!-- Page heading -->
        <div class="mb-6 flex items-center justify-between">
            <div>
                <h2 class="text-xl font-bold text-slate-900 dark:text-slate-100 flex items-center gap-2">
                    <ShieldCheckIcon class="h-6 w-6 text-rose-600" />
                    AutoSSL Manager
                </h2>
                <p class="mt-1 text-sm text-slate-500">
                    Tum sertifikalar, Let's Encrypt rate-limit takibi, force-renew ve RBL kontrol.
                </p>
            </div>
            <Link
                :href="route('admin.ssl.index')"
                class="text-sm text-rose-600 hover:underline"
            >
                ← SSL Manager
            </Link>
        </div>

        <!-- LE Server Rate Limit Banner -->
        <div
            :class="[
                'mb-6 rounded-xl border p-4 shadow-sm',
                server_rate_limit.near_limit
                    ? 'border-amber-300 bg-amber-50 dark:border-amber-700 dark:bg-amber-900/30'
                    : 'border-emerald-300 bg-emerald-50 dark:border-emerald-700 dark:bg-emerald-900/30',
            ]"
        >
            <div class="flex items-center justify-between gap-4 flex-wrap">
                <div class="flex items-center gap-3">
                    <BoltIcon
                        :class="[
                            'h-6 w-6',
                            server_rate_limit.near_limit ? 'text-amber-600' : 'text-emerald-600',
                        ]"
                    />
                    <div>
                        <div class="text-sm font-semibold text-slate-900 dark:text-slate-100">
                            Let's Encrypt Sunucu Kapasitesi
                        </div>
                        <div class="text-xs text-slate-600 dark:text-slate-400">
                            Son 1 saatte {{ server_rate_limit.orders_last_hour }} / 300 yeni order
                            <span v-if="server_rate_limit.near_limit" class="font-semibold text-amber-700 dark:text-amber-300">
                                — yakin limit, yenileme yavaslat
                            </span>
                        </div>
                    </div>
                </div>
                <div class="font-mono text-2xl font-bold text-slate-900 dark:text-slate-100">
                    {{ server_rate_limit.capacity_remaining }}
                    <span class="text-xs font-normal text-slate-500">kalan</span>
                </div>
            </div>
            <div class="mt-3 h-2 rounded-full bg-slate-200 dark:bg-slate-700 overflow-hidden">
                <div
                    :class="[capacityBarClass, 'h-2 rounded-full transition-all duration-500']"
                    :style="{ width: capacityPct + '%' }"
                ></div>
            </div>
        </div>

        <!-- Stat grid -->
        <div class="mb-6 grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-6">
            <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm dark:border-slate-700 dark:bg-slate-900">
                <div class="text-xs text-slate-500">Toplam</div>
                <div class="font-mono text-2xl font-bold text-slate-800 dark:text-slate-100">{{ stats.total }}</div>
            </div>
            <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm dark:border-slate-700 dark:bg-slate-900">
                <div class="text-xs text-emerald-600">Aktif</div>
                <div class="font-mono text-2xl font-bold text-emerald-600">{{ stats.active }}</div>
            </div>
            <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm dark:border-slate-700 dark:bg-slate-900">
                <div class="text-xs text-amber-600">Yakin (30g)</div>
                <div class="font-mono text-2xl font-bold text-amber-600">{{ stats.expiring_30d }}</div>
            </div>
            <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm dark:border-slate-700 dark:bg-slate-900">
                <div class="text-xs text-red-600">Suresi Dolmus</div>
                <div class="font-mono text-2xl font-bold text-red-600">{{ stats.expired }}</div>
            </div>
            <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm dark:border-slate-700 dark:bg-slate-900">
                <div class="text-xs text-rose-700">Basarisiz (7g)</div>
                <div class="font-mono text-2xl font-bold text-rose-700">{{ stats.failed_last_7d }}</div>
            </div>
            <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm dark:border-slate-700 dark:bg-slate-900">
                <div class="text-xs text-purple-600">Rate-Limited</div>
                <div class="font-mono text-2xl font-bold text-purple-600">{{ stats.rate_limited }}</div>
            </div>
        </div>

        <!-- Filters + Bulk bar -->
        <div class="mb-4 flex flex-wrap items-center gap-3 rounded-xl border border-slate-200 bg-white p-4 shadow-sm dark:border-slate-700 dark:bg-slate-900">
            <input
                v-model="filterSearch"
                @keyup.enter="applyFilters"
                type="text"
                placeholder="Domain ara..."
                class="rounded-lg border border-slate-200 bg-slate-50 px-3 py-2 text-sm text-slate-700 focus:outline-none focus:ring-2 focus:ring-rose-500 dark:border-slate-600 dark:bg-slate-800 dark:text-slate-300"
            />
            <select
                v-model="filterStatus"
                class="rounded-lg border border-slate-200 bg-slate-50 px-3 py-2 text-sm text-slate-700 focus:outline-none focus:ring-2 focus:ring-rose-500 dark:border-slate-600 dark:bg-slate-800 dark:text-slate-300"
            >
                <option value="">Tum Durumlar</option>
                <option value="active">Aktif</option>
                <option value="expired">Suresi Dolmus</option>
                <option value="error">Hatali</option>
                <option value="rate_limited">Rate-Limited</option>
                <option value="renewing">Yenileniyor</option>
                <option value="pending">Bekliyor</option>
            </select>
            <select
                v-model="filterExpiring"
                class="rounded-lg border border-slate-200 bg-slate-50 px-3 py-2 text-sm text-slate-700 focus:outline-none focus:ring-2 focus:ring-rose-500 dark:border-slate-600 dark:bg-slate-800 dark:text-slate-300"
            >
                <option value="">Tum Vadeler</option>
                <option value="30">30 gun icinde</option>
                <option value="60">60 gun icinde</option>
                <option value="90">90 gun icinde</option>
            </select>
            <select
                v-model="filterAutoRenew"
                class="rounded-lg border border-slate-200 bg-slate-50 px-3 py-2 text-sm text-slate-700 focus:outline-none focus:ring-2 focus:ring-rose-500 dark:border-slate-600 dark:bg-slate-800 dark:text-slate-300"
            >
                <option value="">Auto-Renew (Tumu)</option>
                <option value="1">Acik</option>
                <option value="0">Kapali</option>
            </select>
            <button
                @click="applyFilters"
                class="rounded-lg bg-rose-600 px-4 py-2 text-sm font-semibold text-white hover:bg-rose-700"
            >
                Filtrele
            </button>
            <button
                @click="resetFilters"
                class="rounded-lg border border-slate-200 px-3 py-2 text-sm text-slate-600 hover:bg-slate-50 dark:border-slate-600 dark:text-slate-300 dark:hover:bg-slate-800"
            >
                Sifirla
            </button>

            <div class="ml-auto flex items-center gap-3">
                <span class="text-xs text-slate-500">
                    {{ selectedIds.size }} secili
                </span>
                <button
                    @click="bulkRenewSelected"
                    :disabled="selectedIds.size === 0"
                    class="inline-flex items-center gap-2 rounded-lg bg-rose-600 px-4 py-2 text-sm font-semibold text-white hover:bg-rose-700 disabled:opacity-40 disabled:cursor-not-allowed"
                >
                    <ArrowPathIcon class="h-4 w-4" />
                    Toplu Yenile ({{ selectedIds.size }})
                </button>
            </div>
        </div>

        <!-- Cert table -->
        <div class="rounded-xl border border-slate-200 bg-white shadow-sm dark:border-slate-700 dark:bg-slate-900 overflow-x-auto">
            <table class="min-w-full divide-y divide-slate-200 dark:divide-slate-700 text-sm">
                <thead class="bg-slate-50 dark:bg-slate-800">
                    <tr>
                        <th class="px-3 py-3 w-8">
                            <input
                                type="checkbox"
                                :checked="allSelected"
                                @change="toggleSelectAll"
                                class="h-4 w-4 rounded border-slate-300 text-rose-600 focus:ring-rose-500"
                            />
                        </th>
                        <th class="px-3 py-3 text-left font-semibold text-slate-600 dark:text-slate-400">Domain</th>
                        <th class="px-3 py-3 text-left font-semibold text-slate-600 dark:text-slate-400">Hesap</th>
                        <th class="px-3 py-3 text-left font-semibold text-slate-600 dark:text-slate-400">Saglayici</th>
                        <th class="px-3 py-3 text-left font-semibold text-slate-600 dark:text-slate-400">Kalan</th>
                        <th class="px-3 py-3 text-center font-semibold text-slate-600 dark:text-slate-400">Auto</th>
                        <th class="px-3 py-3 text-left font-semibold text-slate-600 dark:text-slate-400">Son Deneme</th>
                        <th class="px-3 py-3 text-left font-semibold text-slate-600 dark:text-slate-400">Durum</th>
                        <th class="px-3 py-3 text-right font-semibold text-slate-600 dark:text-slate-400">Islemler</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100 dark:divide-slate-800">
                    <tr v-if="certificates.length === 0">
                        <td colspan="9" class="py-10 text-center text-slate-400">
                            Sertifika bulunamadi.
                        </td>
                    </tr>
                    <tr
                        v-for="cert in certificates"
                        :key="cert.id"
                        :class="[
                            'hover:bg-slate-50 dark:hover:bg-slate-800/50 transition-colors',
                            cert.has_problem ? 'bg-red-50/40 dark:bg-red-950/20' : '',
                        ]"
                    >
                        <td class="px-3 py-3">
                            <input
                                type="checkbox"
                                :checked="selectedIds.has(cert.id)"
                                @change="toggleSelect(cert.id)"
                                class="h-4 w-4 rounded border-slate-300 text-rose-600 focus:ring-rose-500"
                            />
                        </td>
                        <td class="px-3 py-3 font-mono text-slate-800 dark:text-slate-200">
                            <Link
                                :href="route('admin.ssl.autossl.show', cert.id)"
                                class="hover:underline"
                            >
                                {{ cert.domain_name ?? cert.common_name }}
                            </Link>
                            <span
                                v-if="cert.has_problem"
                                class="ml-2 inline-flex items-center gap-1 rounded bg-red-100 px-1.5 py-0.5 text-[10px] font-semibold text-red-700"
                            >
                                <ExclamationTriangleIcon class="h-3 w-3" />
                                Sorun Var
                            </span>
                        </td>
                        <td class="px-3 py-3 text-slate-600 dark:text-slate-400">
                            {{ cert.account_username ?? '—' }}
                        </td>
                        <td class="px-3 py-3 text-slate-600 dark:text-slate-400">
                            {{ issuerLabel(cert.issuer) }}
                        </td>
                        <td class="px-3 py-3 font-mono" :class="daysClass(cert.days_until_expiry)">
                            {{ daysLabel(cert.days_until_expiry) }}
                        </td>
                        <td class="px-3 py-3 text-center">
                            <button
                                @click="toggleAutoRenew(cert)"
                                :title="cert.auto_renew ? 'Otomatik yenileme acik' : 'Otomatik yenileme kapali'"
                                class="inline-flex"
                            >
                                <CheckCircleIcon v-if="cert.auto_renew" class="h-5 w-5 text-emerald-500" />
                                <NoSymbolIcon v-else class="h-5 w-5 text-slate-400" />
                            </button>
                        </td>
                        <td class="px-3 py-3 text-xs text-slate-500">
                            {{ shortDate(cert.last_renewal_attempt_at) }}
                            <span v-if="cert.renewal_attempt_count > 0" class="ml-1 text-rose-500">
                                ×{{ cert.renewal_attempt_count }}
                            </span>
                        </td>
                        <td class="px-3 py-3">
                            <span :class="['inline-flex rounded-full px-2 py-0.5 text-xs font-semibold', statusBadge(cert.status)]">
                                {{ statusLabel(cert.status) }}
                            </span>
                            <div
                                v-if="cert.is_rate_limited"
                                class="mt-1 inline-flex items-center gap-1 text-[10px] text-purple-700"
                            >
                                <SignalSlashIcon class="h-3 w-3" />
                                Rate-Limited
                            </div>
                        </td>
                        <td class="px-3 py-3">
                            <div class="flex justify-end gap-1">
                                <Link
                                    :href="route('admin.ssl.autossl.show', cert.id)"
                                    title="Detay"
                                    class="rounded p-1.5 text-slate-600 hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors"
                                >
                                    <EyeIcon class="h-4 w-4" />
                                </Link>
                                <button
                                    @click="forceRenewOne(cert)"
                                    title="Force Renew"
                                    class="rounded p-1.5 text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900/30 transition-colors"
                                >
                                    <ArrowPathIcon class="h-4 w-4" />
                                </button>
                                <button
                                    @click="checkRblOne(cert)"
                                    title="RBL/Blocklist Kontrol"
                                    class="rounded p-1.5 text-amber-600 hover:bg-amber-50 dark:hover:bg-amber-900/30 transition-colors"
                                >
                                    <ExclamationTriangleIcon class="h-4 w-4" />
                                </button>
                            </div>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </AdminLayout>
</template>
