<template>
    <div class="space-y-6">
        <Head title="Institutions" />

        <div class="rounded-2xl border border-slate-200 bg-white p-6">
            <div class="flex flex-wrap items-start justify-between gap-4">
                <div>
                    <h2 class="text-lg font-semibold">Institution Management</h2>
                    <p class="text-sm text-slate-500">
                        Maintain issuer profiles and BIN configurations.
                    </p>
                </div>
                <button
                    class="rounded-lg bg-slate-900 px-4 py-2 text-xs font-semibold text-white"
                    type="button"
                    @click="openCreate"
                >
                    Add Institution
                </button>
            </div>

            <div class="mt-6 overflow-hidden rounded-lg border border-slate-100">
                <table class="w-full text-left text-sm">
                    <thead class="bg-slate-50 text-slate-500">
                        <tr>
                            <th class="px-4 py-3">Name</th>
                            <th class="px-4 py-3">BIN</th>
                            <th class="px-4 py-3">Status</th>
                            <th class="px-4 py-3">Created</th>
                            <th class="px-4 py-3 text-right">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr
                            v-for="institution in institutions"
                            :key="institution.id"
                            class="border-t border-slate-100"
                        >
                            <td class="px-4 py-3 font-semibold text-slate-700">
                                {{ institution.name }}
                            </td>
                            <td class="px-4 py-3 text-slate-600">
                                {{ institution.bin }}
                            </td>
                            <td class="px-4 py-3">
                                <span
                                    class="rounded-full px-2 py-1 text-[10px] font-semibold"
                                    :class="
                                        institution.status === 'active'
                                            ? 'bg-emerald-100 text-emerald-700'
                                            : 'bg-slate-200 text-slate-600'
                                    "
                                >
                                    {{ institution.status }}
                                </span>
                            </td>
                            <td class="px-4 py-3 text-slate-500">
                                {{ institution.created_at || '—' }}
                            </td>
                            <td class="px-4 py-3 text-right">
                                <button
                                    class="rounded-lg border border-slate-200 px-3 py-1.5 text-xs font-semibold text-slate-700 hover:bg-slate-50"
                                    type="button"
                                    @click="openEdit(institution)"
                                >
                                    Edit
                                </button>
                            </td>
                        </tr>
                        <tr v-if="institutions.length === 0">
                            <td
                                class="px-4 py-6 text-center text-sm text-slate-500"
                                colspan="5"
                            >
                                No institutions configured yet.
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <div
            v-if="showModal"
            class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4"
        >
            <div class="w-full max-w-xl rounded-2xl bg-white p-6">
                <div class="flex items-start justify-between gap-4">
                    <div>
                        <h3 class="text-lg font-semibold">
                            {{ isEditing ? 'Edit Institution' : 'Add Institution' }}
                        </h3>
                        <p class="text-sm text-slate-500">
                            Maintain issuer profile details and BIN settings.
                        </p>
                    </div>
                    <button
                        class="rounded-lg border border-slate-200 px-2 py-1 text-xs text-slate-500"
                        type="button"
                        @click="closeModal"
                    >
                        Close
                    </button>
                </div>

                <form class="mt-6 space-y-4" @submit.prevent="submit">
                    <div class="grid gap-4 md:grid-cols-2">
                        <div>
                            <label class="text-sm font-medium">Institution Name</label>
                            <input
                                v-model="form.name"
                                type="text"
                                class="mt-2 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
                                placeholder="e.g. Apex Bank"
                            />
                            <p v-if="form.errors.name" class="mt-1 text-xs text-red-600">
                                {{ form.errors.name }}
                            </p>
                        </div>
                        <div>
                            <label class="text-sm font-medium">BIN</label>
                            <input
                                v-model="form.bin"
                                type="text"
                                class="mt-2 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
                                placeholder="629900"
                            />
                            <p v-if="form.errors.bin" class="mt-1 text-xs text-red-600">
                                {{ form.errors.bin }}
                            </p>
                        </div>
                    </div>
                    <div>
                        <label class="text-sm font-medium">Card Settings (JSON)</label>
                        <textarea
                            v-model="cardSettingsJson"
                            rows="4"
                            class="mt-2 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm font-mono"
                            placeholder='{"expiry_years":5}'
                        ></textarea>
                        <p
                            v-if="cardSettingsError"
                            class="mt-1 text-xs text-red-600"
                        >
                            {{ cardSettingsError }}
                        </p>
                    </div>
                    <div>
                        <label class="text-sm font-medium">Status</label>
                        <select
                            v-model="form.status"
                            class="mt-2 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
                        >
                            <option value="active">Active</option>
                            <option value="inactive">Inactive</option>
                        </select>
                        <p v-if="form.errors.status" class="mt-1 text-xs text-red-600">
                            {{ form.errors.status }}
                        </p>
                    </div>
                    <div class="flex justify-end gap-2">
                        <button
                            class="rounded-lg border border-slate-200 px-4 py-2 text-xs font-semibold text-slate-700"
                            type="button"
                            @click="closeModal"
                        >
                            Cancel
                        </button>
                        <button
                            class="rounded-lg bg-slate-900 px-4 py-2 text-xs font-semibold text-white"
                            type="submit"
                            :disabled="form.processing"
                        >
                            {{ isEditing ? 'Save Changes' : 'Create Institution' }}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref } from 'vue';
import { Head, useForm } from '@inertiajs/vue3';
import AuthenticatedLayout from '../../Layouts/AuthenticatedLayout.vue';

defineOptions({
    layout: (h, page) =>
        h(AuthenticatedLayout, { title: 'Institutions' }, () => page),
});

const props = defineProps({
    institutions: {
        type: Array,
        default: () => [],
    },
});

const form = useForm({
    id: null,
    name: '',
    bin: '',
    status: 'active',
    card_settings: {},
});

const showModal = ref(false);
const isEditing = ref(false);
const cardSettingsJson = ref('{}');
const cardSettingsError = ref('');

const openCreate = () => {
    isEditing.value = false;
    form.reset();
    form.clearErrors();
    cardSettingsJson.value = '{}';
    cardSettingsError.value = '';
    showModal.value = true;
};

const openEdit = (institution) => {
    isEditing.value = true;
    form.clearErrors();
    form.id = institution.id;
    form.name = institution.name;
    form.bin = institution.bin;
    form.status = institution.status;
    form.card_settings = institution.card_settings || {};
    cardSettingsJson.value = JSON.stringify(form.card_settings, null, 2);
    cardSettingsError.value = '';
    showModal.value = true;
};

const closeModal = () => {
    showModal.value = false;
};

const submit = () => {
    cardSettingsError.value = '';
    if (cardSettingsJson.value.trim()) {
        try {
            form.card_settings = JSON.parse(cardSettingsJson.value);
        } catch (error) {
            cardSettingsError.value = 'Card settings must be valid JSON.';
            return;
        }
    } else {
        form.card_settings = {};
    }

    if (isEditing.value) {
        form.put(`/institutions/${form.id}`, {
            preserveScroll: true,
            onSuccess: () => {
                showModal.value = false;
            },
        });
    } else {
        form.post('/institutions', {
            preserveScroll: true,
            onSuccess: () => {
                showModal.value = false;
            },
        });
    }
};
</script>
