import React, { createContext, useContext, useState, useCallback, useEffect, useMemo } from 'react';
import { useAuth } from '../auth/AuthProvider';
import { GATEWAY_URL, MANAGEMENT_URL } from '../auth/authConfig';

// ─── Navigation structure ─────────────────────────────────────────────────────
export const CATEGORY_TABS = {
    dashboard: [
        { id: 'overview',        label: 'Overview' },
    ],
    campaigns: [
        { id: 'myCampaigns',     label: 'My Campaigns' },
        { id: 'newCampaign',     label: '+ New Campaign' },
    ],
    performance: [
        { id: 'metrics',         label: 'Metrics' },
        { id: 'recommendations', label: 'Recommendations' },
    ],
    billing: [
        { id: 'invoices',        label: 'Invoices' },
    ],
    documents: [
        { id: 'myDocuments',     label: 'My Documents' },
    ],
    support: [
        { id: 'help',            label: 'Help & FAQs' },
    ],
};

export const CATEGORY_LABELS = {
    dashboard:   'Dashboard',
    campaigns:   'Campaigns',
    performance: 'Performance',
    billing:     'Billing',
    documents:   'Documents',
    support:     'Support',
};

// ─── Context ──────────────────────────────────────────────────────────────────
const ClientContext = createContext(null);

export function useAdmin() {
    const ctx = useContext(ClientContext);
    if (!ctx) throw new Error('useAdmin must be used within ClientProvider');
    return ctx;
}

// ─── Provider ─────────────────────────────────────────────────────────────────
export function AdminProvider({ children }) {
    const { sessionUser, sessionToken, signOut } = useAuth();

    const [activeCategory, setActiveCategory] = useState('dashboard');
    const [activeTab, setActiveTab]           = useState('overview');
    const [collapsed, setCollapsed]           = useState(false);
    const [data, setData]                     = useState(null);
    const [loading, setLoading]               = useState(false);
    const [error, setError]                   = useState(null);
    const [refreshKey, setRefreshKey]         = useState(0);
    const [wizardId, setWizardId]             = useState(null);

    // ─── API call — session token Bearer to Gateway ───────────────────────────
    const apiCall = useCallback(async (urlOrPath, methodOrOpts = 'GET', body = null) => {
        if (!sessionToken) return { ok: false, error: 'Not authenticated' };

        // Support options-object form for FormData / rawResponse
        let method, reqBody, isFormData, rawResponse, base;
        if (methodOrOpts !== null && typeof methodOrOpts === 'object') {
            method      = methodOrOpts.method || 'GET';
            rawResponse = !!methodOrOpts.rawResponse;
            const b     = methodOrOpts.body ?? null;
            isFormData  = b instanceof FormData;
            reqBody     = isFormData ? b : (b ? JSON.stringify(b) : null);
            base        = methodOrOpts.mgmt ? MANAGEMENT_URL : GATEWAY_URL;
        } else {
            method      = methodOrOpts;
            rawResponse = false;
            isFormData  = false;
            reqBody     = body ? JSON.stringify(body) : null;
            base        = GATEWAY_URL;
        }

        const url = urlOrPath.startsWith('http') ? urlOrPath : `${base}${urlOrPath}`;
        const headers = { 'Authorization': `Bearer ${sessionToken}` };
        if (!isFormData) headers['Content-Type'] = 'application/json';

        try {
            const res = await fetch(url, { method, headers, body: reqBody || undefined });

            if (!res.ok) {
                if (rawResponse) return null;
                const text = await res.text();
                if (res.status !== 404) console.error(`[Client] HTTP ${res.status}:`, text.substring(0, 200));
                return { ok: false, error: `HTTP ${res.status}` };
            }

            if (rawResponse) return res;
            return await res.json();
        } catch (err) {
            console.error('[Client] Network error:', err.message);
            return rawResponse ? null : { ok: false, error: 'Network error' };
        }
    }, [sessionToken]);

    const handleSelectCategory = useCallback((catId) => {
        setActiveCategory(catId);
        const tabs = CATEGORY_TABS[catId];
        if (tabs?.length > 0) setActiveTab(tabs[0].id);
        setData(null);
        setError(null);
    }, []);

    const handleSelectTab = useCallback((tabId) => {
        setActiveTab(tabId);
        setData(null);
        setError(null);
    }, []);

    const refresh = useCallback(() => setRefreshKey(k => k + 1), []);

    const value = useMemo(() => ({
        session: sessionUser,
        user: sessionUser,
        signOut,

        activeCategory, activeTab, collapsed,
        setActiveCategory: handleSelectCategory,
        setActiveTab: handleSelectTab,
        setCollapsed,
        tabs: CATEGORY_TABS[activeCategory] || [],

        data, loading, error, refresh,
        apiCall,

        // Convenience: client identity from session
        clientId:   sessionUser?.clientId,
        clientName: sessionUser?.clientName,

        // Wizard routing
        wizardId, setWizardId,
    }), [
        sessionUser, signOut,
        activeCategory, activeTab, collapsed,
        handleSelectCategory, handleSelectTab,
        data, loading, error, refresh,
        apiCall,
        wizardId,
    ]);

    return <ClientContext.Provider value={value}>{children}</ClientContext.Provider>;
}
