<script setup>
import { computed } from 'vue'
import { useForm } from '@inertiajs/vue3'
import {
    DocumentArrowUpIcon,
    ExclamationTriangleIcon,
    CheckBadgeIcon,
} from '@heroicons/vue/24/outline'

/**
 * Manuel cert + key install — kullanıcı kendi sertifika otoritesinden aldığı
 * 3rd-party cert'i (Comodo, Sectigo, RapidSSL, Let's Encrypt elle, vs.) yapıştırır.
 *
 * Backend tarafı SslProvisioner::installManual():
 *   1. openssl_x509_parse  — cert metadata
 *   2. openssl_x509_check_private_key  — cert ↔ key match
 *   3. CN/SAN kapsama kontrolü  — cert bu domain'i kapsıyor mu?
 *   4. sysapi('cert-install-manual')  — dosyaya yaz
 *   5. ssl_certificates upsert (issuer='custom', auto_renew=false)
 */
const props = defineProps({
    allDomains: { type: Array, default: () => [] },
})

const form = useForm({
    domain_id: null,
    certificate: '',
    private_key: '',
    chain: '',
})

const submit = () => form.post(route('customer.ssl.manual-install'), {
    preserveScroll: true,
    onSuccess: () => form.reset(),
})

const canSubmit = computed(() =>
    form.domain_id !== null
    && form.certificate.trim().length > 64
    && form.private_key.trim().length > 64
)

const pasteFromClipboard = async (field) => {
    try {
        const text = await navigator.clipboard.readText()
        form[field] = text
    } catch {
        // permission may be denied; ignore
    }
}
</script>

<template>
    <div class="rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
        <div class="mb-4 flex items-center gap-2">
            <DocumentArrowUpIcon class="h-5 w-5 text-indigo-600" />
            <h3 class="text-base font-semibold text-slate-900">Manuel Sertifika Yükleme</h3>
        </div>

        <p class="mb-5 text-sm text-slate-600">
            Comodo, Sectigo, RapidSSL gibi sağlayıcılardan aldığınız ücretli sertifikayı veya
            kendi PKI'nızdan ürettiğiniz cert'i bu formdan yükleyin.
        </p>

        <div class="mb-5 flex items-start gap-2 rounded-lg bg-amber-50 p-3 text-sm text-amber-900">
            <ExclamationTriangleIcon class="h-5 w-5 flex-shrink-0 text-amber-600" />
            <div>
                <strong>Önemli:</strong> Bu sertifikalar otomatik yenilenmez. Süresi dolmadan önce
                aynı işlemi tekrar yapmanız gerekir. Otomatik yenileme için <em>"AutoSSL"</em> seçeneğini kullanın.
            </div>
        </div>

        <form @submit.prevent="submit" class="space-y-4">
            <!-- Domain seçici -->
            <div>
                <label class="block text-sm font-medium text-slate-700">Domain <span class="text-red-600">*</span></label>
                <select
                    v-model="form.domain_id"
                    required
                    class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
                >
                    <option :value="null">Seçin...</option>
                    <option v-for="d in allDomains" :key="d.id" :value="d.id">{{ d.name }}</option>
                </select>
                <p v-if="form.errors.domain_id" class="mt-1 text-xs text-red-600">{{ form.errors.domain_id }}</p>
            </div>

            <!-- Cert -->
            <div>
                <div class="flex items-center justify-between">
                    <label class="text-sm font-medium text-slate-700">Sertifika (PEM) <span class="text-red-600">*</span></label>
                    <button type="button" @click="pasteFromClipboard('certificate')" class="text-xs text-indigo-600 hover:text-indigo-700">
                        Panodan yapıştır
                    </button>
                </div>
                <textarea
                    v-model="form.certificate"
                    placeholder="-----BEGIN CERTIFICATE-----&#10;MIIDXTCCAkW...&#10;-----END CERTIFICATE-----"
                    required
                    class="mt-1 block h-32 w-full rounded-lg border border-slate-300 px-3 py-2 font-mono text-xs text-slate-800 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
                ></textarea>
                <p v-if="form.errors.certificate" class="mt-1 text-xs text-red-600">{{ form.errors.certificate }}</p>
            </div>

            <!-- Key -->
            <div>
                <div class="flex items-center justify-between">
                    <label class="text-sm font-medium text-slate-700">Private Key (PEM) <span class="text-red-600">*</span></label>
                    <button type="button" @click="pasteFromClipboard('private_key')" class="text-xs text-indigo-600 hover:text-indigo-700">
                        Panodan yapıştır
                    </button>
                </div>
                <textarea
                    v-model="form.private_key"
                    placeholder="-----BEGIN RSA PRIVATE KEY-----&#10;MIIEpAIBAAKC...&#10;-----END RSA PRIVATE KEY-----"
                    required
                    class="mt-1 block h-32 w-full rounded-lg border border-red-300 bg-red-50/30 px-3 py-2 font-mono text-xs text-slate-800 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
                ></textarea>
                <p v-if="form.errors.private_key" class="mt-1 text-xs text-red-600">{{ form.errors.private_key }}</p>
                <p class="mt-1 text-xs text-slate-500">Bu key sunucuda şifrelenerek saklanır.</p>
            </div>

            <!-- Chain -->
            <div>
                <div class="flex items-center justify-between">
                    <label class="text-sm font-medium text-slate-700">CA Bundle / Intermediate Chain (isteğe bağlı)</label>
                    <button type="button" @click="pasteFromClipboard('chain')" class="text-xs text-indigo-600 hover:text-indigo-700">
                        Panodan yapıştır
                    </button>
                </div>
                <textarea
                    v-model="form.chain"
                    placeholder="-----BEGIN CERTIFICATE-----&#10;Intermediate CA cert...&#10;-----END CERTIFICATE-----"
                    class="mt-1 block h-24 w-full rounded-lg border border-slate-300 px-3 py-2 font-mono text-xs text-slate-800 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
                ></textarea>
                <p class="mt-1 text-xs text-slate-500">Yoksa boş bırakın — tarayıcılarda "untrusted" uyarısı çıkabilir.</p>
            </div>

            <div class="flex items-center justify-between rounded-lg bg-slate-50 p-3 text-xs text-slate-600">
                <span class="flex items-center gap-1.5">
                    <CheckBadgeIcon class="h-4 w-4 text-emerald-600" />
                    Sertifika ile key panel tarafından <strong>openssl ile doğrulanır</strong>.
                </span>
            </div>

            <div class="flex justify-end gap-2">
                <button
                    type="submit"
                    :disabled="!canSubmit || form.processing"
                    class="inline-flex items-center gap-2 rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700 disabled:opacity-50"
                >
                    <DocumentArrowUpIcon class="h-4 w-4" />
                    {{ form.processing ? 'Yükleniyor...' : 'Doğrula ve Yükle' }}
                </button>
            </div>
        </form>
    </div>
</template>
