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

        <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">Product Management</h2>
                    <p class="text-sm text-slate-500">
                        Define product tiers and issuance behavior per institution.
                    </p>
                </div>
                <button
                    class="rounded-lg bg-slate-900 px-4 py-2 text-xs font-semibold text-white"
                    type="button"
                    @click="openCreate"
                >
                    Add Product
                </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">Product</th>
                            <th class="px-4 py-3">Code</th>
                            <th class="px-4 py-3">Institution</th>
                            <th class="px-4 py-3">Default Limits</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="product in products"
                            :key="product.id"
                            class="border-t border-slate-100"
                        >
                            <td class="px-4 py-3 font-semibold text-slate-700">
                                {{ product.name }}
                            </td>
                            <td class="px-4 py-3 text-slate-600">
                                {{ product.product_code }}
                            </td>
                            <td class="px-4 py-3 text-slate-500">
                                {{ product.institution?.name || '—' }}
                            </td>
                            <td class="px-4 py-3 text-slate-600">
                                {{ product.product_limits?.length || 0 }} txn type(s)
                            </td>
                            <td class="px-4 py-3">
                                <span
                                    class="rounded-full px-2 py-1 text-[10px] font-semibold"
                                    :class="
                                        product.status === 'active'
                                            ? 'bg-emerald-100 text-emerald-700'
                                            : 'bg-slate-200 text-slate-600'
                                    "
                                >
                                    {{ product.status }}
                                </span>
                            </td>
                            <td class="px-4 py-3 text-slate-500">
                                {{ product.created_at || '—' }}
                            </td>
                            <td class="px-4 py-3 text-right">
                                <div class="inline-flex items-center gap-2">
                                    <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(product)"
                                    >
                                        Edit
                                    </button>
                                    <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="openLimitSettings(product)"
                                    >
                                        Limit Settings
                                    </button>
                                </div>
                            </td>
                        </tr>
                        <tr v-if="products.length === 0">
                            <td
                                class="px-4 py-6 text-center text-sm text-slate-500"
                                colspan="7"
                            >
                                No products 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 Product' : 'Add Product' }}
                        </h3>
                        <p class="text-sm text-slate-500">
                            Map products to institutions with customizable 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>
                        <label class="text-sm font-medium">Institution</label>
                        <select
                            v-model="form.institution_id"
                            class="mt-2 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
                        >
                            <option value="">Select institution</option>
                            <option
                                v-for="institution in institutions"
                                :key="institution.id"
                                :value="institution.id"
                            >
                                {{ institution.name }} • {{ institution.bin }}
                            </option>
                        </select>
                        <p
                            v-if="form.errors.institution_id"
                            class="mt-1 text-xs text-red-600"
                        >
                            {{ form.errors.institution_id }}
                        </p>
                    </div>
                    <div class="grid gap-4 md:grid-cols-2">
                        <div>
                            <label class="text-sm font-medium">Product 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="PAYROLL"
                            />
                            <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">Product Code</label>
                            <input
                                v-model="form.product_code"
                                type="text"
                                class="mt-2 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
                                placeholder="PRD-PAYROLL"
                            />
                            <p
                                v-if="form.errors.product_code"
                                class="mt-1 text-xs text-red-600"
                            >
                                {{ form.errors.product_code }}
                            </p>
                        </div>
                    </div>
                    <div>
                        <label class="text-sm font-medium">Product Settings (JSON)</label>
                        <textarea
                            v-model="productSettingsJson"
                            rows="4"
                            class="mt-2 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm font-mono"
                            placeholder='{"channels":["ATM","POS"]}'
                        ></textarea>
                        <p
                            v-if="productSettingsError"
                            class="mt-1 text-xs text-red-600"
                        >
                            {{ productSettingsError }}
                        </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 Product' }}
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <div
            v-if="showLimitModal"
            class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4"
        >
            <div class="w-full max-w-6xl rounded-2xl bg-white p-6">
                <div class="flex items-start justify-between gap-4">
                    <div>
                        <h3 class="text-lg font-semibold">
                            Limit Settings
                        </h3>
                        <p class="text-sm text-slate-500">
                            Configure default limits for {{ selectedProduct?.name || 'this product' }}.
                        </p>
                    </div>
                    <button
                        class="rounded-lg border border-slate-200 px-2 py-1 text-xs text-slate-500"
                        type="button"
                        @click="closeLimitModal"
                    >
                        Close
                    </button>
                </div>

                <div class="mt-4 flex items-center justify-between">
                    <p class="text-xs text-slate-500">
                        These defaults are copied when cards are generated.
                    </p>
                    <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="addLimitRow"
                    >
                        Add Txn Type
                    </button>
                </div>

                <div class="mt-3 overflow-x-auto rounded-lg border border-slate-100">
                    <table class="min-w-[1120px] text-left text-xs">
                        <thead class="bg-slate-50 text-slate-500">
                            <tr>
                                <th class="px-3 py-2">Txn Type</th>
                                <th class="px-3 py-2">Per Txn</th>
                                <th class="px-3 py-2">Daily</th>
                                <th class="px-3 py-2">Weekly</th>
                                <th class="px-3 py-2">Monthly</th>
                                <th class="px-3 py-2">Quarterly</th>
                                <th class="px-3 py-2">Semi-Annual</th>
                                <th class="px-3 py-2">Annual</th>
                                <th class="px-3 py-2 text-right">Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr
                                v-for="(row, index) in limitForm.product_limits"
                                :key="index"
                                class="border-t border-slate-100"
                            >
                                <td class="px-3 py-2">
                                    <input
                                        v-model="row.txn_type"
                                        type="text"
                                        class="w-36 rounded-lg border border-slate-200 px-2 py-1 text-xs uppercase"
                                        placeholder="PURCHASE"
                                    />
                                </td>
                                <td
                                    v-for="field in limitFields"
                                    :key="field.key"
                                    class="px-3 py-2"
                                >
                                    <input
                                        v-model="row[field.key]"
                                        type="number"
                                        min="0"
                                        step="0.01"
                                        class="w-24 rounded-lg border border-slate-200 px-2 py-1 text-xs"
                                    />
                                </td>
                                <td class="px-3 py-2 text-right">
                                    <button
                                        class="rounded-lg border border-red-200 px-2 py-1 text-[11px] font-semibold text-red-600 hover:bg-red-50"
                                        type="button"
                                        @click="removeLimitRow(index)"
                                    >
                                        Remove
                                    </button>
                                </td>
                            </tr>
                            <tr v-if="limitForm.product_limits.length === 0">
                                <td
                                    class="px-4 py-4 text-center text-xs text-slate-400"
                                    colspan="9"
                                >
                                    No default limits yet.
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <p
                    v-if="limitForm.errors.product_limits || limitForm.errors['product_limits.0.txn_type']"
                    class="mt-2 text-xs text-red-600"
                >
                    {{ limitForm.errors.product_limits || limitForm.errors['product_limits.0.txn_type'] }}
                </p>

                <div class="mt-5 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="closeLimitModal"
                    >
                        Cancel
                    </button>
                    <button
                        class="rounded-lg bg-slate-900 px-4 py-2 text-xs font-semibold text-white"
                        type="button"
                        :disabled="limitForm.processing"
                        @click="saveLimitSettings"
                    >
                        {{ limitForm.processing ? 'Saving...' : 'Save Limit Settings' }}
                    </button>
                </div>
            </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: 'Products' }, () => page),
});

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

const form = useForm({
    id: null,
    institution_id: '',
    name: '',
    product_code: '',
    status: 'active',
    product_settings: {},
    product_limits: [],
});

const showModal = ref(false);
const isEditing = ref(false);
const productSettingsJson = ref('{}');
const productSettingsError = ref('');
const showLimitModal = ref(false);
const selectedProduct = ref(null);

const limitFields = [
    { key: 'per_transaction_limit' },
    { key: 'daily_limit' },
    { key: 'weekly_limit' },
    { key: 'monthly_limit' },
    { key: 'quarterly_limit' },
    { key: 'semi_annual_limit' },
    { key: 'annual_limit' },
];

const normalizeLimitRow = (row = {}) => ({
    txn_type: (row.txn_type || '').toString().toUpperCase(),
    per_transaction_limit: row.per_transaction_limit ?? 0,
    daily_limit: row.daily_limit ?? 0,
    weekly_limit: row.weekly_limit ?? 0,
    monthly_limit: row.monthly_limit ?? 0,
    quarterly_limit: row.quarterly_limit ?? 0,
    semi_annual_limit: row.semi_annual_limit ?? 0,
    annual_limit: row.annual_limit ?? 0,
});

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

const openEdit = (product) => {
    isEditing.value = true;
    form.clearErrors();
    form.id = product.id;
    form.institution_id = product.institution?.id || '';
    form.name = product.name;
    form.product_code = product.product_code;
    form.status = product.status;
    form.product_settings = product.product_settings || {};
    productSettingsJson.value = JSON.stringify(form.product_settings, null, 2);
    productSettingsError.value = '';
    showModal.value = true;
};

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

const limitForm = useForm({
    id: null,
    institution_id: '',
    name: '',
    product_code: '',
    status: 'active',
    product_settings: {},
    product_limits: [],
});

const openLimitSettings = (product) => {
    selectedProduct.value = product;
    limitForm.clearErrors();
    limitForm.id = product.id;
    limitForm.institution_id = product.institution?.id || '';
    limitForm.name = product.name;
    limitForm.product_code = product.product_code;
    limitForm.status = product.status;
    limitForm.product_settings = product.product_settings || {};
    limitForm.product_limits = (product.product_limits || []).map(normalizeLimitRow);
    showLimitModal.value = true;
};

const closeLimitModal = () => {
    showLimitModal.value = false;
    selectedProduct.value = null;
};

const addLimitRow = () => {
    limitForm.product_limits.push(normalizeLimitRow());
};

const removeLimitRow = (index) => {
    limitForm.product_limits.splice(index, 1);
};

const submit = () => {
    productSettingsError.value = '';
    if (productSettingsJson.value.trim()) {
        try {
            form.product_settings = JSON.parse(productSettingsJson.value);
        } catch (error) {
            productSettingsError.value = 'Product settings must be valid JSON.';
            return;
        }
    } else {
        form.product_settings = {};
    }

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

const saveLimitSettings = () => {
    limitForm.product_limits = limitForm.product_limits
        .map((row) => normalizeLimitRow(row))
        .filter((row) => row.txn_type);

    limitForm.put(`/products/${limitForm.id}`, {
        preserveScroll: true,
        onSuccess: () => {
            closeLimitModal();
        },
    });
};
</script>
