<script setup>
import { computed, reactive, ref, watch } from 'vue';
import { Head, router, useForm } from '@inertiajs/vue3';
import AdminLayout from '@/Layouts/AdminLayout.vue';
import AppCard from '@/Components/ui/AppCard.vue';
import AppTable from '@/Components/ui/AppTable.vue';
import AppTabs from '@/Components/ui/AppTabs.vue';
import PrimaryButton from '@/Components/PrimaryButton.vue';

const props = defineProps({
    filters: Object,
    categories: Array,
    networks: Array,
    vendors: Array,
    autoFixReport: { type: Object, default: null },
    planCodeImportReport: { type: Object, default: null },
    selectedScope: { type: Object, default: null },
    rules: { type: Array, default: () => [] },
});

const query = reactive({
    category_id: props.filters?.category_id || '',
    network_id: props.filters?.network_id || '',
});
const activeTab = ref('routing');

const blankRule = () => ({
    vendor_id: '',
    status: 'active',
    force_vendor: false,
});

const form = useForm({
    category_id: query.category_id,
    network_id: query.network_id,
    rules: props.rules?.length
        ? props.rules.map((row) => ({
            id: row.id,
            vendor_id: row.vendor_id || '',
            status: row.status || 'active',
            force_vendor: !!row.force_vendor,
        }))
        : [blankRule()],
});

const autoFixForm = useForm({
    category_id: query.category_id,
    network_id: query.network_id,
});

const importForm = useForm({
    category_id: query.category_id,
    network_id: query.network_id,
    default_vendor_id: '',
    csv_file: null,
});

watch(
    () => props.rules,
    (rows) => {
        form.category_id = query.category_id;
        form.network_id = query.network_id;
        form.rules = rows?.length
            ? rows.map((row) => ({
                id: row.id,
                vendor_id: row.vendor_id || '',
                status: row.status || 'active',
                force_vendor: !!row.force_vendor,
            }))
            : [blankRule()];
    },
    { immediate: false }
);

watch(
    () => [query.category_id, query.network_id],
    () => {
        form.category_id = query.category_id;
        form.network_id = query.network_id;
        autoFixForm.category_id = query.category_id;
        autoFixForm.network_id = query.network_id;
        importForm.category_id = query.category_id;
        importForm.network_id = query.network_id;
    }
);

const applyFilters = () => {
    router.get(route('admin.mappings.index'), query, { preserveState: true, replace: true });
};

const addRuleRow = () => {
    form.rules.push(blankRule());
};

const removeRuleRow = (index) => {
    form.rules.splice(index, 1);
    if (!form.rules.length) {
        form.rules.push(blankRule());
    }
};

const moveRuleRow = (index, direction) => {
    const target = index + direction;
    if (target < 0 || target >= form.rules.length) return;
    const [row] = form.rules.splice(index, 1);
    form.rules.splice(target, 0, row);
};

const setForcedRuleRow = (index) => {
    form.rules = form.rules.map((row, rowIndex) => ({
        ...row,
        force_vendor: rowIndex === index ? !row.force_vendor : false,
    }));
};

const isVendorAlreadySelected = (vendorId, currentIndex) =>
    form.rules.some((row, rowIndex) => rowIndex !== currentIndex && String(row.vendor_id || '') === String(vendorId));

const saveRules = () => {
    if (!form.category_id) return;
    form.put(route('admin.mappings.service-rules.update'), { preserveScroll: true });
};

const runAutoFix = () => {
    if (!autoFixForm.category_id) return;

    autoFixForm.post(route('admin.mappings.auto-fix'), {
        preserveScroll: true,
    });
};

const setImportFile = (event) => {
    const file = event?.target?.files?.[0] || null;
    importForm.csv_file = file;
};

const runPlanCodeImport = () => {
    if (!importForm.category_id || !importForm.csv_file) return;

    importForm.post(route('admin.mappings.plan-codes.import'), {
        preserveScroll: true,
        forceFormData: true,
        onSuccess: () => {
            importForm.reset('csv_file');
        },
    });
};

const fieldError = (path) => form.errors[path] || null;

const selectedCategory = computed(() =>
    props.categories.find((category) => String(category.id) === String(query.category_id)) || null
);

const routingSubtitle = computed(() => {
    const slug = selectedCategory.value?.slug || '';

    if (slug === 'airtime_vtu') {
        return 'Airtime is amount-based. Configure vendor priority/fallback here by network. No plan ID/code is required.';
    }

    return 'This page does not store vendor plan IDs. For plan-based services, set vendor plan IDs in Plan Manager.';
});

const pageTabs = computed(() => ([
    { key: 'routing', label: 'Routing Rules' },
    { key: 'tools', label: 'Tools' },
]));
</script>

<template>
    <Head title="Routing Rules" />

    <AdminLayout>
        <template #header>
            <div>
                <h2 class="text-xl font-semibold text-gray-800">Routing Rules</h2>
                <p class="mt-1 text-sm text-gray-500">
                    Choose which vendors should handle each service type (and optional network) in priority order.
                </p>
            </div>
        </template>

        <div class="mx-auto max-w-7xl space-y-6">
            <AppTabs v-model="activeTab" :tabs="pageTabs" aria-label="Routing sections" />

            <AppCard v-if="activeTab === 'routing'" title="How to use" subtitle="Beginner-friendly routing setup">
                <div class="grid gap-3 text-sm text-gray-600 md:grid-cols-3">
                    <div class="rounded-lg border border-gray-200 bg-gray-50 p-3">1. Select a <strong>Category</strong> (for example Data SME, Airtime VTU, Electricity).</div>
                    <div class="rounded-lg border border-gray-200 bg-gray-50 p-3">2. Optionally select a <strong>Network</strong> (MTN/Airtel/Glo/9mobile) for network-specific routing.</div>
                    <div class="rounded-lg border border-gray-200 bg-gray-50 p-3">3. Add vendors in row order. Top row = <strong>Priority 1</strong>, next row = fallback. For data/cable plans, add vendor plan IDs in <strong>Plan Manager</strong>.</div>
                </div>
            </AppCard>

            <AppCard v-if="activeTab === 'tools' && autoFixReport" title="Last Auto-Fix Result" subtitle="What was fixed in the previous run">
                <div class="grid gap-3 text-sm text-gray-600 md:grid-cols-2 lg:grid-cols-4">
                    <div class="rounded-lg border border-emerald-200 bg-emerald-50 p-3">
                        <div class="text-xs uppercase tracking-wide text-emerald-700">Service mappings created</div>
                        <div class="mt-1 text-lg font-semibold text-emerald-800">{{ autoFixReport.created_service_mappings || 0 }}</div>
                    </div>
                    <div class="rounded-lg border border-blue-200 bg-blue-50 p-3">
                        <div class="text-xs uppercase tracking-wide text-blue-700">Service mappings updated</div>
                        <div class="mt-1 text-lg font-semibold text-blue-800">{{ autoFixReport.updated_service_mappings || 0 }}</div>
                    </div>
                    <div class="rounded-lg border border-emerald-200 bg-emerald-50 p-3">
                        <div class="text-xs uppercase tracking-wide text-emerald-700">Plan mappings created</div>
                        <div class="mt-1 text-lg font-semibold text-emerald-800">{{ autoFixReport.created_plan_mappings || 0 }}</div>
                    </div>
                    <div class="rounded-lg border border-amber-200 bg-amber-50 p-3">
                        <div class="text-xs uppercase tracking-wide text-amber-700">Still needs manual plan code</div>
                        <div class="mt-1 text-lg font-semibold text-amber-800">{{ autoFixReport.unresolved_plans_count || 0 }}</div>
                    </div>
                </div>

                <div
                    v-if="(autoFixReport.unresolved_plans || []).length"
                    class="mt-3 rounded-lg border border-amber-200 bg-amber-50 p-3 text-xs text-amber-900"
                >
                    <div class="font-semibold">Plans requiring manual Vendor Plan ID / Code:</div>
                    <div class="mt-2 max-h-32 overflow-auto">
                        <div v-for="item in autoFixReport.unresolved_plans" :key="`unresolved-${item.plan_id}`">
                            #{{ item.plan_id }} - {{ item.plan_name }}
                        </div>
                    </div>
                </div>
            </AppCard>

            <AppCard v-if="activeTab === 'tools'" title="Bulk Plan Codes Import" subtitle="Upload CSV to create/update vendor plan IDs quickly">
                <div class="grid gap-3 md:grid-cols-4">
                    <select v-model="importForm.default_vendor_id" class="rounded-md border-gray-300 text-sm shadow-sm">
                        <option value="">Use vendor_id from CSV</option>
                        <option v-for="vendor in vendors" :key="`default-vendor-${vendor.id}`" :value="vendor.id">
                            {{ vendor.name }} ({{ vendor.type }})
                        </option>
                    </select>

                    <input
                        type="file"
                        accept=".csv,text/csv"
                        class="rounded-md border border-gray-300 px-3 py-2 text-sm"
                        @change="setImportFile"
                    />

                    <button
                        type="button"
                        class="rounded-md border border-indigo-300 bg-indigo-50 px-3 py-2 text-sm text-indigo-800"
                        :disabled="importForm.processing || !query.category_id || !importForm.csv_file"
                        @click="runPlanCodeImport"
                    >
                        {{ importForm.processing ? 'Importing...' : 'Import Plan Codes CSV' }}
                    </button>

                    <div class="rounded-md border border-gray-200 bg-gray-50 px-3 py-2 text-xs text-gray-600">
                        <div class="font-semibold text-gray-800">CSV header format</div>
                        <div class="font-mono text-[11px]">plan_id,vendor_id,vendor_plan_code,priority,status,force_vendor</div>
                    </div>
                </div>
                <p class="mt-2 text-xs text-gray-500">
                    Use selected scope only. Rows outside the selected category/network are skipped.
                </p>
                <p v-if="importForm.errors.csv_file" class="mt-1 text-xs text-rose-600">{{ importForm.errors.csv_file }}</p>
            </AppCard>

            <AppCard
                v-if="activeTab === 'tools' && planCodeImportReport"
                title="Last Plan Code Import Result"
                subtitle="Summary of the most recent CSV import"
            >
                <div class="grid gap-3 text-sm text-gray-600 md:grid-cols-2 lg:grid-cols-5">
                    <div class="rounded-lg border border-gray-200 bg-gray-50 p-3">
                        <div class="text-xs uppercase tracking-wide text-gray-500">Processed</div>
                        <div class="mt-1 text-lg font-semibold text-gray-800">{{ planCodeImportReport.processed_rows || 0 }}</div>
                    </div>
                    <div class="rounded-lg border border-emerald-200 bg-emerald-50 p-3">
                        <div class="text-xs uppercase tracking-wide text-emerald-700">Created</div>
                        <div class="mt-1 text-lg font-semibold text-emerald-800">{{ planCodeImportReport.created || 0 }}</div>
                    </div>
                    <div class="rounded-lg border border-blue-200 bg-blue-50 p-3">
                        <div class="text-xs uppercase tracking-wide text-blue-700">Updated</div>
                        <div class="mt-1 text-lg font-semibold text-blue-800">{{ planCodeImportReport.updated || 0 }}</div>
                    </div>
                    <div class="rounded-lg border border-slate-200 bg-slate-50 p-3">
                        <div class="text-xs uppercase tracking-wide text-slate-600">Skipped</div>
                        <div class="mt-1 text-lg font-semibold text-slate-800">{{ planCodeImportReport.skipped || 0 }}</div>
                    </div>
                    <div class="rounded-lg border border-rose-200 bg-rose-50 p-3">
                        <div class="text-xs uppercase tracking-wide text-rose-700">Errors</div>
                        <div class="mt-1 text-lg font-semibold text-rose-800">{{ planCodeImportReport.error_count || 0 }}</div>
                    </div>
                </div>

                <div
                    v-if="(planCodeImportReport.errors || []).length"
                    class="mt-3 max-h-36 overflow-auto rounded-lg border border-rose-200 bg-rose-50 p-3 text-xs text-rose-900"
                >
                    <div class="font-semibold">Import errors:</div>
                    <div v-for="item in planCodeImportReport.errors" :key="`import-error-${item.row}-${item.message}`" class="mt-1">
                        Row {{ item.row }}: {{ item.message }}
                    </div>
                </div>
            </AppCard>

            <AppCard v-if="activeTab === 'routing'" title="Select Routing Scope">
                <div class="grid gap-3 md:grid-cols-4">
                    <select v-model="query.category_id" class="rounded-md border-gray-300 text-sm shadow-sm">
                        <option value="">Select category</option>
                        <option v-for="category in categories" :key="category.id" :value="category.id">
                            {{ category.name }}
                        </option>
                    </select>

                    <select v-model="query.network_id" class="rounded-md border-gray-300 text-sm shadow-sm">
                        <option value="">All / General (Category Only)</option>
                        <option v-for="network in networks" :key="network.id" :value="network.id">
                            {{ network.name }}
                        </option>
                    </select>

                    <button type="button" class="rounded-md border border-gray-300 px-3 py-2 text-sm" @click="applyFilters">
                        Load Rules
                    </button>

                    <div class="rounded-md border border-gray-200 bg-gray-50 px-3 py-2 text-xs text-gray-600">
                        <div class="font-semibold text-gray-800">Current Scope</div>
                        <div v-if="selectedScope">{{ selectedScope.category?.name }} / {{ selectedScope.network?.name || 'Category Only' }}</div>
                        <div v-else>Select a category to begin</div>
                    </div>
                </div>
            </AppCard>

            <AppCard v-if="activeTab === 'routing' && query.category_id" title="Vendor Priority (Routing Order)" :subtitle="routingSubtitle">
                <div class="mb-4 flex flex-wrap justify-end gap-2">
                    <button
                        type="button"
                        class="rounded-md border border-emerald-300 bg-emerald-50 px-3 py-2 text-sm text-emerald-800"
                        :disabled="autoFixForm.processing || !query.category_id"
                        @click="runAutoFix"
                    >
                        {{ autoFixForm.processing ? 'Running Auto-Fix...' : 'Auto-Fix Missing Routes' }}
                    </button>
                    <button type="button" class="rounded-md border border-gray-300 px-3 py-2 text-sm" @click="addRuleRow">+ Add Vendor</button>
                </div>

                <AppTable>
                    <thead class="bg-gray-50">
                        <tr class="text-left text-xs font-semibold uppercase tracking-wide text-gray-500">
                            <th class="px-4 py-3">Priority</th>
                            <th class="px-4 py-3">Vendor</th>
                            <th class="px-4 py-3">Status</th>
                            <th class="px-4 py-3">Force</th>
                            <th class="px-4 py-3 text-right">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-100 text-sm">
                        <tr v-for="(row, index) in form.rules" :key="row.id || `rule-${index}`">
                            <td class="px-4 py-3">
                                <div class="text-xs font-semibold text-gray-700">{{ index + 1 }}</div>
                            </td>
                            <td class="px-4 py-3">
                                <select v-model="row.vendor_id" class="w-full rounded-md border-gray-300 text-sm shadow-sm">
                                    <option value="">Select vendor</option>
                                    <option v-for="vendor in vendors" :key="vendor.id" :value="vendor.id" :disabled="isVendorAlreadySelected(vendor.id, index)">
                                        {{ vendor.name }} ({{ vendor.type }}){{ isVendorAlreadySelected(vendor.id, index) ? ' - already selected' : '' }}
                                    </option>
                                </select>
                                <p v-if="fieldError(`rules.${index}.vendor_id`)" class="mt-1 text-xs text-rose-600">{{ fieldError(`rules.${index}.vendor_id`) }}</p>
                            </td>
                            <td class="px-4 py-3">
                                <select v-model="row.status" class="rounded-md border-gray-300 text-sm shadow-sm">
                                    <option value="active">active</option>
                                    <option value="inactive">inactive</option>
                                </select>
                            </td>
                            <td class="px-4 py-3">
                                <label class="inline-flex items-center gap-2 text-xs text-gray-700">
                                    <input
                                        :checked="!!row.force_vendor"
                                        type="checkbox"
                                        class="rounded border-gray-300"
                                        @change="setForcedRuleRow(index)"
                                    />
                                    Force
                                </label>
                            </td>
                            <td class="px-4 py-3">
                                <div class="flex justify-end gap-2">
                                    <button type="button" class="rounded border px-2 py-1 text-xs" :disabled="index === 0" @click="moveRuleRow(index, -1)">↑</button>
                                    <button type="button" class="rounded border px-2 py-1 text-xs" :disabled="index === form.rules.length - 1" @click="moveRuleRow(index, 1)">↓</button>
                                    <button type="button" class="rounded border px-2 py-1 text-xs text-rose-700" @click="removeRuleRow(index)">Remove</button>
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </AppTable>

                <div class="mt-4 flex justify-end">
                    <PrimaryButton :disabled="form.processing || !form.category_id" @click="saveRules">
                        {{ form.processing ? 'Saving...' : 'Save Routing Rules' }}
                    </PrimaryButton>
                </div>
            </AppCard>
        </div>
    </AdminLayout>
</template>
