<script setup>
import {reactive, ref, watch} from 'vue'

// Import Components
import PricingVariants from '../PricingVariants.vue'
import ProductVersioning from '../ProductVersioning.vue'
import ProductFiles from '../ProductFiles.vue'
import ProductAddons from '../ProductAddons.vue'
import CheckoutFields from '../CheckoutFields.vue'
import {BILLING_CYCLES, BILLING_TYPES, TRIAL_UNITS} from '../../../constants.js'

// --- Props ---
const props = defineProps(['productType', 'initialData', 'initialCheckoutFields'])

// --- Component State ---
const activeTab = ref('plans')
const tabs = [
    { id: 'plans', label: 'Pricing Plans', icon: 'payments' },
    { id: 'files', label: 'Files & Deliverables', icon: 'folder_zip' },
    { id: 'addons', label: 'Addons', icon: 'extension' },
    { id: 'checkout_fields', label: 'Checkout Fields', icon: 'dynamic_form' },
]

// Checkout Fields
const checkoutFieldsRef = ref(null)

// Feature Toggles
const features = reactive({
    versioning: false, // Default to Simple Files
    bundle: false      // Default: Not a bundle
})

const bundleItems = ref([])
const availableProducts = window.ChargePandaConfig?.available_products || []

// 1. Multiple Plans (Recurring)
const plans = ref([
    { 
        id: crypto.randomUUID(), 
        name: 'Monthly Plan', 
        price: '19.00', 
        setupFee: '0.00',
        billing: BILLING_CYCLES.BILLING_CYCLE_MONTHLY, 
        trial: true,
        trialDays: 14,
        trialUnit: TRIAL_UNITS.TRIAL_DURATION_DAYS,
        issueLicense: false,
        prices: [
            {
                id: crypto.randomUUID(),
                tierName: 'Monthly',
                price: '19.00',
                setupFee: '0.00',
                billing: BILLING_CYCLES.BILLING_CYCLE_MONTHLY,
                billingCycleCount: '',
                trial: true,
                trialDays: 14,
                trialUnit: TRIAL_UNITS.TRIAL_DURATION_DAYS
            }
        ],
        planAddons: []
    }
])

// 2. Releases (Versioning Mode)
const releases = ref([])

// 3. Simple Files (Non-Versioning Mode)
const simpleFiles = ref([])

// 4. Addons
const addons = ref([])

// --- Logic Handlers ---

const handleTabChange = (tabId) => {
    activeTab.value = tabId
}

// Release Handlers
const handleAddRelease = (release) => {
    const newRelease = { ...release, id: release.id || crypto.randomUUID() }
    releases.value.unshift(newRelease) 
}

const handleUpdateRelease = ({ index, release }) => {
    releases.value[index] = release
}

const handleRemoveRelease = (index) => {
    releases.value.splice(index, 1)
}

// Simple File Handlers
const handleAddSimpleFile = (file) => {
    simpleFiles.value.push(file)
}

const handleUpdateSimpleFile = ({ index, file }) => {
    simpleFiles.value[index] = file
}

const handleRemoveSimpleFile = (index) => {
    simpleFiles.value.splice(index, 1)
}

// Addon Handlers
const syncAddonToPlans = (addon) => {
    // 1. Iterate all plans
    plans.value.forEach(plan => {
        const shouldBeInPlan = addon.plan_ids?.includes(plan.id)
        const existingIndex = plan.planAddons?.findIndex(pa => pa.id === addon.id) ?? -1
        
        if (shouldBeInPlan) {
            // Get overrides for this plan
            const overrides = addon.planOverrides?.[plan.id] || {}
            
            if (existingIndex > -1) {
                // Update existing
                plan.planAddons[existingIndex].pricing = overrides
            } else {
                // Add to plan
                if (!plan.planAddons) plan.planAddons = []
                plan.planAddons.push({
                    id: addon.id,
                    pricing: overrides
                })
            }
        } else {
            // Remove from plan if present
            if (existingIndex > -1) {
                plan.planAddons.splice(existingIndex, 1)
            }
        }
    })
}

const handleAddon = (newAddon) => {
    addons.value.push(newAddon)
    syncAddonToPlans(newAddon)
}

const handleUpdateAddon = ({ index, addon }) => {
    addons.value[index] = addon
    syncAddonToPlans(addon)
}

const handleRemoveAddon = (index) => {
    const addonId = addons.value[index].id
    addons.value.splice(index, 1)
    
    // Remove from all plans
    plans.value.forEach(plan => {
        const idx = plan.planAddons?.findIndex(pa => pa.id === addonId)
        if (idx > -1) plan.planAddons.splice(idx, 1)
    })
}

// Plan Handlers (Multiple Plans)
const updatePlan = ({ index, plan }) => {
    if (plans.value[index]) {
        plans.value[index] = { ...plan }
    }
}

const addPlan = (planData) => {
    if (planData) {
        // Use the plan data from the modal
        plans.value.push(planData)
    } else {
        // Fallback: create a default plan
        plans.value.push({ 
            id: crypto.randomUUID(), 
            name: 'New Plan', 
            description: '',
            price: '', 
            billing: BILLING_CYCLES.BILLING_CYCLE_MONTHLY, 
            issueLicense: false,
            prices: [
                {
                    id: crypto.randomUUID(),
                    tierName: '',
                    price: '',
                    setupFee: '0.00',
                    billing: BILLING_CYCLES.BILLING_CYCLE_MONTHLY,
                    billingCycleCount: '',
                    trial: false,
                    trialDays: 14,
                    trialUnit: TRIAL_UNITS.TRIAL_DURATION_DAYS
                }
            ],
            planAddons: []
        })
    }
}

const removePlan = (index) => {
    if (plans.value.length > 1) {
        plans.value.splice(index, 1)
    } else {
        alert('You must have at least one pricing option.')
    }
}

// --- Data Exporter (Payload Construction) ---
const getPayload = () => {
    // 1. Transform Plans
    const transformedPlans = plans.value.map(plan => ({
        name: plan.name,
        description: plan.description || null,
        billing_type: BILLING_TYPES.BILLING_SUBSCRIPTION, // Subscription
        features: [],
        is_licensable: plan.issueLicense || false,
        license_validity: null,
        license_duration: null,
        license_duration_unit: null,
        daily_download_limit: plan.dailyDownloadLimit > 0 ? plan.dailyDownloadLimit : null,
        bundle_product_ids: features.bundle
            ? bundleItems.value.filter(bi => bi.plan_ids.includes(plan.id)).map(bi => bi.product_id)
            : [],
        is_default: plan.id === plans.value[0].id,
        pricing_tiers: plan.prices.map((tier, index) => {
             const isOneTime = tier.billing === BILLING_CYCLES.ONE_TIME;
             return {
                tier_name: isOneTime ? 'Lifetime' : (tier.billing === BILLING_CYCLES.BILLING_CYCLE_MONTHLY ? 'Monthly' : (tier.billing === BILLING_CYCLES.BILLING_CYCLE_YEARLY ? 'Yearly' : 'Custom')),
                price: tier.price,
                setup_fee: tier.setupFee,
                billing_type: isOneTime ? BILLING_TYPES.BILLING_ONETIME : BILLING_TYPES.BILLING_SUBSCRIPTION, 
                billing_cycle: isOneTime ? null : tier.billing, 
                billing_cycle_count: 1, 
                trial_available: tier.trial,
                trial_duration: tier.trialDays,
                trial_duration_unit: tier.trialUnit || TRIAL_UNITS.TRIAL_DURATION_DAYS,
                is_default: index === 0
            }
        })
    }))

    // 2. Transform Addons
    const transformedAddons = addons.value.map(globalAddon => {
        const planIndexes = []
        const pricingOverrides = []
        
        // Check usage in plans
        plans.value.forEach((plan, pIndex) => {
            const planAddon = plan.planAddons?.find(pa => pa.id === globalAddon.id)
            if (planAddon) {
                planIndexes.push(pIndex)
                 if (planAddon.pricing) {
                    plan.prices.forEach((tier, tIndex) => {
                        const overridePrice = planAddon.pricing[tier.billing]
                        if (overridePrice !== undefined && overridePrice !== '') {
                             pricingOverrides.push({
                                 plan_index: pIndex,
                                 tier_index: tIndex,
                                 price: overridePrice
                            })
                        }
                    })
                 }
            }
        })

        return {
            name: globalAddon.name,
            description: globalAddon.description,
            billing_type: globalAddon.billing === BILLING_CYCLES.ONE_TIME ? BILLING_TYPES.ONE_TIME : BILLING_TYPES.SUBSCRIPTION,
            price: globalAddon.price,
            billing_cycle: globalAddon.billing === BILLING_CYCLES.ONE_TIME ? null : globalAddon.billing,
            billing_cycle_count: globalAddon.billing === BILLING_CYCLES.ONE_TIME ? null : 1,
            product_level: false,
            plan_indexes: planIndexes,
            pricing: pricingOverrides
        }
    })

    // 3. Transform Files or Releases
    let transformedFiles = []
    
    if (features.versioning) {
        // Versioning Mode
        transformedFiles = releases.value.map(release => ({
            version: release.version, 
            changelog: release.changelog,
            is_global: release.is_global !== false,
            product_files: release.files.map(f => ({ name: f.name, media_id: f.media_id })), 
            plan_indexes: []
        }))
    } else {
        // Simple Files Mode (Group by plan signature)
        const fileGroups = {} 
        
        simpleFiles.value.forEach(file => {
            const signature = (file.plan_ids || []).sort().join(',')
            if (!fileGroups[signature]) fileGroups[signature] = []
            fileGroups[signature].push(file)
        })
        
        Object.keys(fileGroups).forEach(sig => {
            const groupFiles = fileGroups[sig]
            const planIds = sig ? sig.split(',') : []
            // Find indexes in plans array
            const planIndexes = planIds.map(pid => plans.value.findIndex(p => p.id == pid)).filter(i => i > -1)
            
            if (groupFiles.length > 0) {
                transformedFiles.push({
                    version: null, 
                    changelog: null,
                    is_global: !sig, 
                    product_files: groupFiles.map(f => ({ name: f.name, media_id: f.media_id })),
                    plan_indexes: planIndexes
                })
            }
        })
    }

    return {
        features: {
            versioning: features.versioning,
            bundle: features.bundle
        },
        plans: transformedPlans,
        addons: transformedAddons,
        files: features.bundle ? [] : transformedFiles,
        support_policy: {
            enabled: false // Always disabled for subscriptions
        }
    }
}

const getCheckoutFields = () => checkoutFieldsRef.value?.getPayload() ?? []

// Define Expose for Parent
defineExpose({ getPayload, getCheckoutFields, populateFromData, loadDummyData })

// --- Hydration (Edit Mode) ---
const populateFromData = (data) => {
    console.log('💧 Hydrating SubscriptionMode:', data)

    // 1. Features
    if (data.features) {
        if (data.features.versioning !== undefined) features.versioning = data.features.versioning
        if (data.features.bundle !== undefined) features.bundle = data.features.bundle
    }

    // 2. Plans & Pricing
    if (data.plans && data.plans.length > 0) {
        plans.value = data.plans.map(p => {
            // Map Pricing Tiers to 'prices' array
            const mappedPrices = p.pricing_tiers.map(t => ({
                id: t.id,
                price: t.price,
                setupFee: t.setup_fee,
                billing: t.billing_cycle || BILLING_CYCLES.BILLING_CYCLE_MONTHLY,
                trial: t.trial_available,
                trialDays: t.trial_duration,
                trialUnit: t.trial_duration_unit || TRIAL_UNITS.TRIAL_DURATION_DAYS
            }))

            // Use first tier for plan defaults (display purposes)
            const defaultTier = p.pricing_tiers[0] || {}

            return {
                id: p.id,
                name: p.name,
                description: p.description || '',
                price: defaultTier.price || '', 
                setupFee: defaultTier.setup_fee || '0.00',
                billing: defaultTier.billing_cycle || BILLING_CYCLES.BILLING_CYCLE_MONTHLY, 
                trial: defaultTier.trial_available || false,
                trialDays: defaultTier.trial_duration,
                trialUnit: defaultTier.trial_duration_unit || TRIAL_UNITS.TRIAL_DURATION_DAYS,
                issueLicense: p.is_licensable,
                features: p.features || [], // ← needed by FeatureComparisonMatrix
                dailyDownloadLimit: p.daily_download_limit || null,
                prices: mappedPrices,
                planAddons: []
            }
        })
    }

    // 2b. Reconstruct bundleItems if bundle mode is on
    if (features.bundle && data.plans) {
        const bundleMap = {}
        data.plans.forEach(p => {
            (p.bundle_product_ids || []).forEach(productId => {
                if (!bundleMap[productId]) {
                    const found = availableProducts.find(ap => ap.id === productId)
                    bundleMap[productId] = {
                        product_id: productId,
                        product_name: found?.name || `Product #${productId}`,
                        plan_ids: []
                    }
                }
                bundleMap[productId].plan_ids.push(p.id)
            })
        })
        bundleItems.value = Object.values(bundleMap)
    }

    // 3. Addons
    if (data.addons) {
        addons.value = data.addons.map(a => ({
            id: a.id,
            name: a.name,
            description: a.description,
            price: a.price,
            billing: a.billing_type === BILLING_TYPES.BILLING_ONETIME ? BILLING_CYCLES.ONE_TIME : (a.billing_cycle || BILLING_CYCLES.BILLING_CYCLE_MONTHLY),
            plan_ids: a.plan_ids || []
        }))

        // Sync Addons to Plans (Local State)
        addons.value.forEach(addon => syncAddonToPlans(addon))
    }

    // 4. Files
    if (data.files) {
        if (features.versioning) {
            releases.value = data.files.map(f => ({
                id: f.id,
                version: f.version,
                changelog: f.changelog,
                is_global: f.is_global,
                files: f.product_files.map(pf => ({ name: pf.name, media_id: pf.id, size: pf.size })),
                plan_ids: f.plan_ids
            }))
        } else {
             // Flatten files
            simpleFiles.value = []
            data.files.forEach(f => {
                f.product_files.forEach(pf => {
                    simpleFiles.value.push({
                         name: pf.name,
                         media_id: pf.id,
                         size: pf.size,
                         plan_ids: f.plan_ids
                    })
                })
            })
        }
    }
}

// Watch initialData
watch(() => props.initialData, (newData) => {
    if (newData) {
        populateFromData(newData)
    }
}, { immediate: true })

// --- Demo Data ---
function loadDummyData() {
    plans.value = [
        { 
            id: 'p1', name: 'Starter', price: '19.00', billing: BILLING_CYCLES.BILLING_CYCLE_MONTHLY, trial: true, 
            prices: [{id: 't1', price: '19.00', billing: BILLING_CYCLES.BILLING_CYCLE_MONTHLY}] 
        },
        { 
            id: 'p2', name: 'Pro', price: '49.00', billing: BILLING_CYCLES.BILLING_CYCLE_MONTHLY, trial: false,
            prices: [{id: 't2', price: '49.00', billing: BILLING_CYCLES.BILLING_CYCLE_MONTHLY}] 
        }
    ]
    
    releases.value = [{ 
        id: 'r1', version: 'v2.0', changeLog: 'Major Update', 
        files: [{name: 'app_v2.zip', size: '15MB'}], is_global: true 
    }]
    
    addons.value = [{ id: 'a1', name: 'Priority Support', price: '9.00', billing: BILLING_CYCLES.BILLING_CYCLE_MONTHLY }]

    activeTab.value = 'plans'
}
</script>

<template>
    <div>
        <!-- Tab Navigation -->
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-body p-2">
                <ul class="nav nav-pills nav-fill gap-2">
                    <li class="nav-item" v-for="tab in tabs" :key="tab.id">
                        <button 
                            class="nav-link"
                            :class="{ active: activeTab === tab.id }"
                            @click="handleTabChange(tab.id)"
                        >
                            <span class="material-icons fs-6">{{ tab.icon }}</span>
                            {{ tab.label }}
                        </button>
                    </li>
                </ul>
            </div>
        </div>

        <div class="d-flex flex-column gap-4">
            
            <!-- TAB 1: PLANS -->
            <div v-if="activeTab === 'plans'" class="animate__animated animate__fadeIn">
                


                <PricingVariants 
                    :plans="plans" 
                    :files="releases" 
                    :addons="addons"
                    productType="advanced" 
                    @add-plan="addPlan" 
                    @update-plan="updatePlan"
                    @remove-plan="removePlan" 
                />
            </div>

            <!-- TAB 2: FILES & DELIVERABLES -->
            <div v-if="activeTab === 'files'" class="animate__animated animate__fadeIn">

                <!-- Toggles row -->
                <div class="d-flex align-items-center justify-content-between mb-3 px-1 gap-3 flex-wrap">
                    <div>
                        <h6 class="mb-0 fw-semibold">Deliverables</h6>
                        <p class="small text-secondary mb-0">Manage files for your customers.</p>
                    </div>
                    <div class="d-flex flex-column gap-2">
                        <div class="form-check form-switch mb-0" :style="{ opacity: features.versioning ? 0.45 : 1 }">
                            <input class="form-check-input" type="checkbox" id="featBundleSub" v-model="features.bundle" :disabled="features.versioning">
                            <label class="form-check-label small" for="featBundleSub">Bundle Mode</label>
                        </div>
                        <div class="form-check form-switch mb-0" :style="{ opacity: features.bundle ? 0.45 : 1 }">
                            <input class="form-check-input" type="checkbox" id="featVersioningSub" v-model="features.versioning" :disabled="features.bundle">
                            <label class="form-check-label small" for="featVersioningSub">Enable Release Management (Versioning)</label>
                        </div>
                    </div>
                </div>

                <!-- Bundle Mode -->
                <div v-if="features.bundle" class="animate__animated animate__fadeIn">
                    <ProductFiles
                        :bundleMode="true"
                        :bundleItems="bundleItems"
                        :availableProducts="availableProducts"
                        :plans="plans"
                        pricingMode="variable"
                        @update-bundle-items="bundleItems = $event"
                    />
                </div>

                <!-- Versioning Mode -->
                <div v-else-if="features.versioning" class="animate__animated animate__fadeIn">
                    <ProductVersioning
                        :releases="releases"
                        :plans="plans"
                        pricingMode="variable"
                        @add-release="handleAddRelease"
                        @update-release="handleUpdateRelease"
                        @remove-release="handleRemoveRelease"
                    />
                </div>

                <!-- Simple Files Mode -->
                <div v-else class="animate__animated animate__fadeIn">
                    <ProductFiles
                        :files="simpleFiles"
                        :plans="plans"
                        pricingMode="variable"
                        @add-file="handleAddSimpleFile"
                        @update-file="handleUpdateSimpleFile"
                        @remove-file="handleRemoveSimpleFile"
                    />
                </div>
            </div>

            <!-- TAB 3: ADDONS -->
            <div v-if="activeTab === 'addons'" class="animate__animated animate__fadeIn">
                <ProductAddons
                    :addons="addons"
                    :plans="plans"
                    pricingMode="variable"
                    @add-addon="handleAddon"
                    @update-addon="handleUpdateAddon"
                    @remove-addon="handleRemoveAddon"
                />
            </div>

            <!-- TAB 4: CHECKOUT FIELDS -->
            <div v-if="activeTab === 'checkout_fields'" class="animate__animated animate__fadeIn">
                <CheckoutFields ref="checkoutFieldsRef" :initial-fields="props.initialCheckoutFields || []" />
            </div>
        </div>
    </div>
</template>
