<script setup>
import { computed, ref } from 'vue';
import { Head, useForm } from '@inertiajs/vue3';
import MobileAppLayout from '@/Layouts/MobileAppLayout.vue';
import AppCard from '@/Components/ui/AppCard.vue';

const props = defineProps({
    client: {
        type: Object,
        required: true,
    },
    api: {
        type: Object,
        required: true,
    },
    one_time_secret: {
        type: String,
        default: null,
    },
});

const copiedKey = ref('');
const secretInput = ref('');

const rotateForm = useForm({});

const copyText = async (text, key) => {
    const value = String(text || '').trim();
    if (!value) return;

    try {
        await navigator.clipboard.writeText(value);
    } catch {
        const textarea = document.createElement('textarea');
        textarea.value = value;
        textarea.setAttribute('readonly', '');
        textarea.style.position = 'absolute';
        textarea.style.left = '-9999px';
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
    }

    copiedKey.value = key;
    setTimeout(() => {
        if (copiedKey.value === key) copiedKey.value = '';
    }, 1200);
};

const rotateSecret = () => {
    rotateForm.post(route('app.api-access.rotate'), { preserveScroll: true });
};

const curlSample = computed(() => {
    const sampleBody = JSON.stringify({
        idempotency_key: 'idem-123456',
        category_slug: 'airtime_vtu',
        network_id: 1,
        plan_id: 10,
        phone: '08012345678',
        amount: 500,
    }, null, 2);

    return [
        `POST ${props.api.base_url}/purchase/airtime`,
        'Headers: X-Api-Key, X-Timestamp, X-Nonce, X-Signature',
        'Body:',
        sampleBody,
    ].join('\n');
});

const jsSample = computed(() => {
    return `const method = 'POST';\nconst path = '/api/v1/purchase/airtime';\nconst timestamp = Math.floor(Date.now()/1000).toString();\nconst nonce = crypto.randomUUID();\nconst body = JSON.stringify({ /* payload */ });\nconst bodyHash = sha256(body);\nconst payload = [method, path, timestamp, nonce, bodyHash].join('\\n');\nconst signature = hmacSha256(payload, SECRET);`;
});
</script>

<template>
    <Head title="API Access" />

    <MobileAppLayout title="API Access" subtitle="Manage reseller API keys and request signing">
        <div class="space-y-4">
            <AppCard title="Client Credentials" subtitle="Use these credentials for your external reseller integration.">
                <div class="space-y-3 text-sm">
                    <div class="rounded-xl border border-slate-200 bg-slate-50 p-3">
                        <div class="text-[11px] uppercase tracking-wide text-slate-500">Public Key</div>
                        <div class="mt-1 break-all font-semibold text-slate-900">{{ client.public_key }}</div>
                        <button type="button" class="mt-2 rounded-md border border-slate-300 px-2.5 py-1 text-xs font-semibold text-slate-700" @click="copyText(client.public_key, 'pk')">
                            {{ copiedKey === 'pk' ? 'Copied' : 'Copy Public Key' }}
                        </button>
                    </div>

                    <div class="grid grid-cols-2 gap-2 text-xs">
                        <div class="rounded-xl border border-slate-200 bg-slate-50 p-2.5">
                            <div class="text-slate-500">Status</div>
                            <div class="mt-1 font-semibold text-slate-900 capitalize">{{ client.status }}</div>
                        </div>
                        <div class="rounded-xl border border-slate-200 bg-slate-50 p-2.5">
                            <div class="text-slate-500">Rate limit / min</div>
                            <div class="mt-1 font-semibold text-slate-900">{{ client.rate_limit_per_minute }}</div>
                        </div>
                    </div>

                    <div class="rounded-xl border border-amber-200 bg-amber-50 p-3 text-xs text-amber-900">
                        Secret ends with: <span class="font-semibold">{{ client.secret_last4 || '----' }}</span>. Rotate if secret is exposed.
                    </div>

                    <button
                        type="button"
                        class="inline-flex items-center justify-center rounded-xl bg-slate-900 px-4 py-2.5 text-sm font-semibold text-white hover:bg-slate-800 disabled:opacity-60"
                        :disabled="rotateForm.processing"
                        @click="rotateSecret"
                    >
                        {{ rotateForm.processing ? 'Rotating...' : 'Rotate Secret' }}
                    </button>

                    <div v-if="one_time_secret" class="rounded-xl border border-emerald-200 bg-emerald-50 p-3 text-xs text-emerald-900">
                        <div class="font-semibold">New Secret (shown once)</div>
                        <div class="mt-1 break-all font-mono">{{ one_time_secret }}</div>
                        <button type="button" class="mt-2 rounded-md border border-emerald-300 bg-white px-2.5 py-1 font-semibold text-emerald-800" @click="copyText(one_time_secret, 'secret')">
                            {{ copiedKey === 'secret' ? 'Copied' : 'Copy Secret' }}
                        </button>
                    </div>
                </div>
            </AppCard>

            <AppCard title="Signing Rules" subtitle="Every request must be signed with your secret.">
                <div class="space-y-3 text-xs">
                    <div class="rounded-xl border border-slate-200 bg-slate-50 p-3">
                        <div class="font-semibold text-slate-800">Required Headers</div>
                        <div class="mt-1 text-slate-600">{{ api.headers.join(', ') }}</div>
                    </div>
                    <div class="rounded-xl border border-slate-200 bg-slate-50 p-3">
                        <div class="font-semibold text-slate-800">Signature Format</div>
                        <div class="mt-1 font-mono text-slate-700">{{ api.signature_format }}</div>
                    </div>
                </div>
            </AppCard>

            <AppCard title="Samples" subtitle="Use this as a quick integration guide.">
                <div class="space-y-3 text-xs">
                    <div class="rounded-xl border border-slate-200 bg-slate-50 p-3">
                        <div class="mb-1 font-semibold text-slate-800">Sample Request</div>
                        <pre class="overflow-x-auto whitespace-pre-wrap text-slate-700">{{ curlSample }}</pre>
                    </div>
                    <div class="rounded-xl border border-slate-200 bg-slate-50 p-3">
                        <div class="mb-1 font-semibold text-slate-800">JS Signing Example</div>
                        <pre class="overflow-x-auto whitespace-pre-wrap text-slate-700">{{ jsSample }}</pre>
                    </div>
                </div>
            </AppCard>
        </div>
    </MobileAppLayout>
</template>
