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

const props = defineProps({
    plan: { type: Object, default: null },
    resolvedServiceProviderId: { type: [Number, String, null], default: null },
    vendorMappings: { type: Array, default: () => [] },
    tierPrices: { type: Object, default: () => ({ subscriber: null, reseller: null, agent: null }) },
    networks: Array,
    serviceProviders: { type: Array, default: () => [] },
    categories: Array,
    vendors: Array,
    statuses: Array,
});

const PROVIDER_GROUP_BY_CATEGORY = {
    cable: 'cable',
    electricity: 'electricity',
    epin: 'epin',
};

const isEdit = computed(() => !!props.plan);
const catalogState = reactive({});

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

const initialVendorRows = props.vendorMappings?.length
    ? props.vendorMappings.map((row) => ({
        id: row.id,
        vendor_id: row.vendor_id || '',
        vendor_plan_code: row.vendor_plan_code || '',
        status: row.status || 'active',
        force_vendor: !!row.force_vendor,
    }))
    : [blankVendorRow()];

const form = useForm({
    network_id: props.plan?.network_id || '',
    service_provider_id: props.resolvedServiceProviderId ?? props.plan?.meta_json?.service_provider_id ?? '',
    category_id: props.plan?.category_id || '',
    name: props.plan?.name || '',
    duration_label: props.plan?.duration_label || '',
    status: props.plan?.status || 'available',
    sort_order: props.plan?.sort_order || 0,
    meta_json: {
        ...(props.plan?.meta_json || {}),
        vtpass_service_id: props.plan?.meta_json?.vtpass_service_id || '',
        vtpass_subscription_type: props.plan?.meta_json?.vtpass_subscription_type || '',
        vtpass_quantity: props.plan?.meta_json?.vtpass_quantity || '',
    },
    tier_prices: {
        subscriber: props.tierPrices?.subscriber ?? props.plan?.selling_price ?? '',
        reseller: props.tierPrices?.reseller ?? '',
        agent: props.tierPrices?.agent ?? '',
    },
    vendor_mappings: initialVendorRows,
});

const selectedCategory = computed(() => props.categories.find((c) => Number(c.id) === Number(form.category_id)) || null);
const isDataCategory = computed(() => (selectedCategory.value?.slug || '').startsWith('data_'));

const selectedCategorySlug = computed(() => {
    const selected = props.categories.find((category) => Number(category.id) === Number(form.category_id));
    return selected?.slug || '';
});

const providerGroups = computed(() => [
    ...new Set((props.serviceProviders || []).map((provider) => String(provider.service_group || '')).filter(Boolean)),
]);

const selectedProviderGroup = computed(() => {
    const slug = selectedCategorySlug.value;
    if (!slug) return null;
    if (PROVIDER_GROUP_BY_CATEGORY[slug]) return PROVIDER_GROUP_BY_CATEGORY[slug];
    return providerGroups.value.includes(slug) ? slug : null;
});

const providerOptions = computed(() =>
    (props.serviceProviders || []).filter((provider) => provider.service_group === selectedProviderGroup.value)
);

const addVendorRow = () => {
    form.vendor_mappings.push(blankVendorRow());
};

const removeVendorRow = (index) => {
    form.vendor_mappings.splice(index, 1);
    if (!form.vendor_mappings.length) {
        form.vendor_mappings.push(blankVendorRow());
    }
};

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

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

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

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

const selectedNetworkSlug = computed(() => {
    const selected = props.networks.find((network) => Number(network.id) === Number(form.network_id));
    return selected?.slug || '';
});

const requiresNetwork = computed(() => isDataCategory.value);
const requiresServiceProvider = computed(() => !!selectedProviderGroup.value);
const isVariableAmountCategory = computed(() => ['airtime_vtu', 'electricity'].includes(selectedCategorySlug.value));
const requiresSubscriberPrice = computed(() => !isVariableAmountCategory.value);
const requiresVendorPlanCode = computed(() =>
    ['data_sme', 'data_gifting', 'data_cg', 'data_direct', 'cable'].includes(selectedCategorySlug.value)
);

const supportsVtpassMeta = computed(() =>
    ['data_sme', 'data_gifting', 'data_cg', 'data_direct', 'cable', 'electricity', 'epin'].includes(selectedCategorySlug.value)
);

const subscriberPriceLabel = computed(() => (
    requiresSubscriberPrice.value ? 'Subscriber Price (Default)' : 'Default Price (Optional)'
));

const subscriberPricePlaceholder = computed(() => (
    requiresSubscriberPrice.value ? 'Required' : 'Optional'
));

watch(requiresNetwork, (enabled) => {
    if (!enabled) {
        form.network_id = '';
    }
}, { immediate: true });

watch(requiresServiceProvider, (enabled) => {
    if (!enabled) {
        form.service_provider_id = '';
    }
}, { immediate: true });

watch(selectedProviderGroup, () => {
    if (!requiresServiceProvider.value) return;
    const inScope = providerOptions.value.some((provider) => Number(provider.id) === Number(form.service_provider_id));
    if (!inScope) {
        form.service_provider_id = '';
    }
});

watch(
    () => form.service_provider_id,
    (providerId) => {
        if (!providerId) return;

        const provider = providerOptions.value.find((item) => Number(item.id) === Number(providerId));
        if (!provider) return;

        const vtpassServiceId = provider?.meta_json?.vtpass_service_id;
        if (vtpassServiceId) {
            form.meta_json.vtpass_service_id = String(vtpassServiceId);
        }
    },
    { immediate: true }
);

const setCatalogState = (index, data) => {
    catalogState[index] = {
        loading: false,
        message: '',
        items: [],
        ...(catalogState[index] || {}),
        ...data,
    };
};

const fetchVendorCatalog = async (index) => {
    const row = form.vendor_mappings[index];
    if (!row?.vendor_id) {
        setCatalogState(index, { message: 'Select vendor first.', items: [] });
        return;
    }

    setCatalogState(index, { loading: true, message: 'Fetching plan IDs/codes...', items: [] });

    const vendor = props.vendors.find((item) => Number(item.id) === Number(row.vendor_id));
    if (!vendor) {
        setCatalogState(index, { loading: false, message: 'Vendor not found in active list.', items: [] });
        return;
    }

    const params = new URLSearchParams();
    if (selectedNetworkSlug.value) params.set('network_slug', selectedNetworkSlug.value);
    if (selectedCategorySlug.value) params.set('category_slug', selectedCategorySlug.value);
    if (form.meta_json?.vtpass_service_id) params.set('service_id', String(form.meta_json.vtpass_service_id));

    const href = route('admin.vendors.plan-catalog', vendor.id) + (params.toString() ? `?${params.toString()}` : '');

    try {
        const response = await fetch(href, {
            headers: {
                Accept: 'application/json',
                'X-Requested-With': 'XMLHttpRequest',
            },
        });
        const payload = await response.json();

        setCatalogState(index, {
            loading: false,
            message: payload?.message || (response.ok ? 'Catalog loaded.' : 'Unable to load catalog.'),
            items: Array.isArray(payload?.items) ? payload.items : [],
        });
    } catch (error) {
        setCatalogState(index, {
            loading: false,
            message: 'Plan fetch failed. Check vendor config and network.',
            items: [],
        });
    }
};

const applyCatalogCode = (index, code) => {
    form.vendor_mappings[index].vendor_plan_code = String(code || '');
};

const submit = () => {
    if (isEdit.value) {
        form.put(route('admin.plans.update', props.plan.id));
        return;
    }

    form.post(route('admin.plans.store'));
};
</script>

<template>
    <Head :title="isEdit ? 'Edit Plan' : 'Create Plan'" />

    <AdminLayout>
        <template #header>
            <div class="flex items-center justify-between gap-4">
                <div>
                    <h2 class="text-xl font-semibold text-gray-800">{{ isEdit ? 'Edit Plan' : 'Add Plan' }}</h2>
                    <p class="mt-1 text-sm text-gray-500">Add non-airtime plan details, tier prices, and vendor plan IDs in one screen.</p>
                </div>
                <Link :href="route('admin.plans.index')" class="text-sm text-gray-600 hover:text-gray-900">Back to Plans</Link>
            </div>
        </template>

        <div class="mx-auto max-w-6xl space-y-6">
            <AppCard title="Plan Details" subtitle="Basic setup for the internal plan users will see.">
                <form class="space-y-6" @submit.prevent="submit">
                    <div class="space-y-6">
                        <div class="grid gap-4 md:grid-cols-2">
                        <FormField label="Category" :error="form.errors.category_id">
                            <select v-model="form.category_id" class="w-full 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>
                        </FormField>

                        <FormField
                            v-if="requiresNetwork"
                            label="Network"
                            :error="form.errors.network_id"
                            help="Required for data plans. Telecom networks only."
                        >
                            <select v-model="form.network_id" class="w-full rounded-md border-gray-300 text-sm shadow-sm">
                                <option value="">Select network</option>
                                <option v-for="network in networks" :key="network.id" :value="network.id">{{ network.name }}</option>
                            </select>
                        </FormField>

                        <FormField
                            v-else-if="requiresServiceProvider"
                            label="Provider"
                            :error="form.errors.service_provider_id"
                            help="Provider list is category-specific (for example DSTV/GOTV for cable, IKEDC/KEDCO for electricity)."
                        >
                            <select v-model="form.service_provider_id" class="w-full rounded-md border-gray-300 text-sm shadow-sm">
                                <option value="">Select provider</option>
                                <option v-for="provider in providerOptions" :key="provider.id" :value="provider.id">
                                    {{ provider.name }}
                                </option>
                            </select>
                        </FormField>

                        <FormField
                            v-else
                            label="Provider"
                            help="This category does not require network/provider mapping in Plan Manager."
                        >
                            <input
                                value="Not required"
                                disabled
                                class="w-full rounded-md border-gray-200 bg-gray-50 text-sm text-gray-500 shadow-sm"
                            />
                        </FormField>

                        <FormField label="Plan Name" :error="form.errors.name" help="Example: MTN SME 500MB">
                            <input v-model="form.name" class="w-full rounded-md border-gray-300 text-sm shadow-sm" placeholder="e.g. MTN SME 500MB" />
                        </FormField>

                        <FormField v-if="isDataCategory" label="Duration" :error="form.errors.duration_label" help="Example: 1 day, 7 days, 30 days, 1 month">
                            <input v-model="form.duration_label" class="w-full rounded-md border-gray-300 text-sm shadow-sm" placeholder="e.g. 30 days" />
                        </FormField>

                        <FormField v-else label="Status" :error="form.errors.status">
                            <select v-model="form.status" class="w-full rounded-md border-gray-300 text-sm shadow-sm">
                                <option v-for="status in statuses" :key="status" :value="status">{{ status }}</option>
                            </select>
                        </FormField>

                        <FormField v-if="isDataCategory" label="Status" :error="form.errors.status">
                            <select v-model="form.status" class="w-full rounded-md border-gray-300 text-sm shadow-sm">
                                <option v-for="status in statuses" :key="status" :value="status">{{ status }}</option>
                            </select>
                        </FormField>

                        <FormField label="Sort Order" :error="form.errors.sort_order" help="Lower numbers appear first.">
                            <input v-model="form.sort_order" type="number" min="0" class="w-full rounded-md border-gray-300 text-sm shadow-sm" />
                        </FormField>
                        </div>

                        <div v-if="supportsVtpassMeta" class="rounded-xl border border-sky-200 bg-sky-50/70 p-4">
                            <div class="mb-3">
                                <h3 class="text-sm font-semibold text-gray-900">VTpass Metadata (Optional but recommended)</h3>
                                <p class="mt-1 text-xs text-gray-600">
                                    Set VTpass <span class="font-mono">serviceID</span> per plan/service for accurate routing.
                                    Examples: <span class="font-mono">mtn-data</span>, <span class="font-mono">dstv</span>, <span class="font-mono">ikeja-electric</span>, <span class="font-mono">waec</span>.
                                </p>
                            </div>

                            <div class="grid gap-4 md:grid-cols-3">
                                <FormField label="VTpass serviceID" :error="form.errors['meta_json.vtpass_service_id']">
                                    <input
                                        v-model="form.meta_json.vtpass_service_id"
                                        class="w-full rounded-md border-gray-300 text-sm shadow-sm"
                                        placeholder="e.g. mtn-data / dstv / ikeja-electric"
                                    />
                                </FormField>

                                <FormField
                                    v-if="selectedCategorySlug === 'cable'"
                                    label="VTpass subscription_type"
                                    :error="form.errors['meta_json.vtpass_subscription_type']"
                                    help="For DSTV/GOTV: change or renew."
                                >
                                    <select v-model="form.meta_json.vtpass_subscription_type" class="w-full rounded-md border-gray-300 text-sm shadow-sm">
                                        <option value="">Auto</option>
                                        <option value="change">change</option>
                                        <option value="renew">renew</option>
                                        <option value="renewal">renewal</option>
                                    </select>
                                </FormField>

                                <FormField
                                    v-if="selectedCategorySlug === 'cable'"
                                    label="VTpass quantity"
                                    :error="form.errors['meta_json.vtpass_quantity']"
                                    help="Optional card quantity for supported cable products."
                                >
                                    <input
                                        v-model="form.meta_json.vtpass_quantity"
                                        type="number"
                                        min="1"
                                        max="12"
                                        class="w-full rounded-md border-gray-300 text-sm shadow-sm"
                                        placeholder="1"
                                    />
                                </FormField>
                            </div>
                        </div>
                    </div>

                    <div class="rounded-xl border border-emerald-200 bg-emerald-50/70 p-4">
                        <div class="mb-3">
                            <h3 class="text-sm font-semibold text-gray-900">Tier Pricing</h3>
                            <p class="mt-1 text-xs text-gray-600">
                                <template v-if="requiresSubscriberPrice">
                                    Subscriber Price is the default selling price. Reseller and Agent prices are optional overrides.
                                </template>
                                <template v-else>
                                    This category is amount-based. You can leave Subscriber Price empty and users will enter the amount at purchase time.
                                </template>
                            </p>
                        </div>

                        <div class="grid gap-4 md:grid-cols-3">
                            <FormField
                                :label="subscriberPriceLabel"
                                :error="fieldError('tier_prices.subscriber') || form.errors.tier_prices?.subscriber"
                            >
                                <input
                                    v-model="form.tier_prices.subscriber"
                                    type="number"
                                    min="0"
                                    step="0.01"
                                    class="w-full rounded-md border-gray-300 text-sm shadow-sm"
                                    :placeholder="subscriberPricePlaceholder"
                                />
                            </FormField>

                            <FormField label="Reseller Price" :error="fieldError('tier_prices.reseller') || form.errors.tier_prices?.reseller">
                                <input
                                    v-model="form.tier_prices.reseller"
                                    type="number"
                                    min="0"
                                    step="0.01"
                                    class="w-full rounded-md border-gray-300 text-sm shadow-sm"
                                    placeholder="Optional"
                                />
                            </FormField>

                            <FormField label="Agent Price" :error="fieldError('tier_prices.agent') || form.errors.tier_prices?.agent">
                                <input
                                    v-model="form.tier_prices.agent"
                                    type="number"
                                    min="0"
                                    step="0.01"
                                    class="w-full rounded-md border-gray-300 text-sm shadow-sm"
                                    placeholder="Optional"
                                />
                            </FormField>
                        </div>
                    </div>

                    <div class="rounded-xl border border-gray-200 bg-white p-4">
                        <div class="mb-3 flex flex-wrap items-center justify-between gap-3">
                            <div>
                                <h3 class="text-sm font-semibold text-gray-900">Vendor Plan IDs / Codes</h3>
                                <p class="mt-1 text-xs text-gray-500">
                                    <template v-if="requiresVendorPlanCode">
                                        Add vendor plan codes here. Row order is used as priority (top row = Priority 1).
                                    </template>
                                    <template v-else>
                                        Vendor code is optional for this category. Row order is used as priority (top row = Priority 1).
                                    </template>
                                </p>
                            </div>
                            <button
                                type="button"
                                class="inline-flex items-center rounded-md border border-gray-300 px-3 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50"
                                @click="addVendorRow"
                            >
                                + Add Vendor
                            </button>
                        </div>

                        <div class="space-y-3">
                            <div
                                v-for="(row, index) in form.vendor_mappings"
                                :key="row.id || `row-${index}`"
                                class="rounded-lg border border-gray-200 bg-gray-50/60 p-3"
                            >
                                <div class="mb-3 flex items-center justify-between gap-2">
                                    <div class="text-xs font-semibold uppercase tracking-wide text-gray-500">
                                        Priority {{ index + 1 }}
                                    </div>
                                    <div class="flex items-center gap-2">
                                        <button type="button" class="rounded border px-2 py-1 text-xs" :disabled="index === 0" @click="moveVendorRow(index, -1)">↑</button>
                                        <button type="button" class="rounded border px-2 py-1 text-xs" :disabled="index === form.vendor_mappings.length - 1" @click="moveVendorRow(index, 1)">↓</button>
                                        <button type="button" class="rounded border px-2 py-1 text-xs text-rose-700" @click="removeVendorRow(index)">Remove</button>
                                    </div>
                                </div>

                                <div class="grid gap-4 md:grid-cols-2">
                                    <FormField label="Vendor" :error="fieldError(`vendor_mappings.${index}.vendor_id`)">
                                        <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>
                                    </FormField>

                                    <FormField
                                        :label="requiresVendorPlanCode ? 'Vendor Plan ID / Code' : 'Vendor Plan ID / Code (Optional)'"
                                        :error="fieldError(`vendor_mappings.${index}.vendor_plan_code`)">
                                        <input
                                            v-model="row.vendor_plan_code"
                                            class="w-full rounded-md border-gray-300 text-sm shadow-sm"
                                            :placeholder="requiresVendorPlanCode ? 'e.g. 5001 / MTN_SME_500' : 'Optional for this category'"
                                        />
                                        <div class="mt-2 flex flex-wrap items-center gap-2">
                                            <button
                                                type="button"
                                                class="inline-flex items-center rounded-md border border-indigo-300 bg-indigo-50 px-2.5 py-1 text-xs font-semibold text-indigo-700 hover:bg-indigo-100"
                                                :disabled="catalogState[index]?.loading"
                                                @click="fetchVendorCatalog(index)"
                                            >
                                                {{ catalogState[index]?.loading ? 'Fetching...' : 'Fetch Vendor Plans' }}
                                            </button>
                                            <span v-if="catalogState[index]?.message" class="text-xs text-gray-600">
                                                {{ catalogState[index].message }}
                                            </span>
                                        </div>
                                        <div v-if="(catalogState[index]?.items || []).length" class="mt-2 rounded-md border border-gray-200 bg-white p-2">
                                            <div class="mb-1 text-[11px] font-semibold uppercase tracking-wide text-gray-500">Select from fetched plans</div>
                                            <select class="w-full rounded-md border-gray-300 text-sm shadow-sm" @change="applyCatalogCode(index, $event.target.value)">
                                                <option value="">Choose vendor plan code</option>
                                                <option v-for="item in catalogState[index].items" :key="`${index}-${item.code}`" :value="item.code">
                                                    {{ item.code }} - {{ item.label }}{{ item.hint ? ` (${item.hint})` : '' }}
                                                </option>
                                            </select>
                                        </div>
                                    </FormField>

                                    <FormField label="Row Status" :error="fieldError(`vendor_mappings.${index}.status`)">
                                        <select v-model="row.status" class="w-full rounded-md border-gray-300 text-sm shadow-sm">
                                            <option value="active">active</option>
                                            <option value="inactive">inactive</option>
                                        </select>
                                    </FormField>

                                    <div class="rounded-md border border-amber-200 bg-amber-50 px-3 py-2">
                                        <label class="flex items-center gap-2 text-sm text-gray-700">
                                            <input
                                                :checked="!!row.force_vendor"
                                                type="checkbox"
                                                class="rounded border-gray-300"
                                                @change="setForcedVendorRow(index)"
                                            />
                                            <span>Force this vendor (advanced)</span>
                                        </label>
                                        <p class="mt-1 text-xs text-gray-500">Optional: use only when you want to override normal routing for this plan.</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="flex justify-end">
                        <PrimaryButton :disabled="form.processing">{{ form.processing ? 'Saving...' : 'Save Plan' }}</PrimaryButton>
                    </div>
                </form>
            </AppCard>
        </div>
    </AdminLayout>
</template>
