'use client';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { cmsApi } from '../../lib/api.js';
const EMPTY_BRAND_VOICE = {
    enabled: false,
    name: '',
    tone: '',
    audience: '',
    guidelines: '',
    sampleText: '',
};
function formFromResponse(res) {
    return {
        defaultProviderId: res.settings.defaultProviderId ?? '',
        defaultModelId: res.settings.defaultModelId ?? '',
        features: res.settings.features.map((f) => ({
            ...f,
            modelId: f.modelId ?? '',
            providerId: f.providerId ?? '',
        })),
        monthlyTokenLimit: typeof res.settings.budget.monthlyTokenLimit === 'number'
            ? String(res.settings.budget.monthlyTokenLimit)
            : '',
        brandVoice: {
            enabled: res.settings.brandVoice?.enabled ?? false,
            name: res.settings.brandVoice?.name ?? '',
            tone: res.settings.brandVoice?.tone ?? '',
            audience: res.settings.brandVoice?.audience ?? '',
            guidelines: res.settings.brandVoice?.guidelines ?? '',
            sampleText: res.settings.brandVoice?.sampleText ?? '',
        },
    };
}
const EMPTY_FORM = {
    defaultProviderId: '',
    defaultModelId: '',
    features: [],
    monthlyTokenLimit: '',
    brandVoice: { ...EMPTY_BRAND_VOICE },
};
/** A brand voice with no content and disabled clears the stored profile (send null). */
function brandVoiceIsEmpty(bv) {
    return (!bv.enabled &&
        !bv.name.trim() &&
        !bv.tone.trim() &&
        !bv.audience.trim() &&
        !bv.guidelines.trim() &&
        !bv.sampleText.trim());
}
export function useAiSettings(canEdit) {
    const [loading, setLoading] = useState(true);
    const [loadError, setLoadError] = useState(null);
    const [providers, setProviders] = useState([]);
    const [models, setModels] = useState([]);
    const [usage, setUsage] = useState(null);
    const [defaultModel, setDefaultModel] = useState(null);
    const [baseline, setBaseline] = useState(EMPTY_FORM);
    const [form, setForm] = useState(EMPTY_FORM);
    const [saveState, setSaveState] = useState('idle');
    const [saveError, setSaveError] = useState(null);
    const [busyProviderId, setBusyProviderId] = useState(null);
    const [reloadKey, setReloadKey] = useState(0);
    const loadModels = useCallback(async () => {
        const res = await cmsApi('/ai/models');
        if (!res.error && res.data)
            setModels(res.data.models ?? []);
    }, []);
    useEffect(() => {
        let cancelled = false;
        setLoading(true);
        setLoadError(null);
        Promise.all([
            cmsApi('/ai/settings'),
            cmsApi('/ai/models'),
            cmsApi('/ai/usage/summary'),
        ])
            .then(([settingsRes, modelsRes, usageRes]) => {
            if (cancelled)
                return;
            if (settingsRes.error) {
                setLoadError(settingsRes.error);
                return;
            }
            if (settingsRes.data) {
                const loaded = formFromResponse(settingsRes.data);
                setBaseline(loaded);
                setForm(loaded);
                setProviders(settingsRes.data.providers ?? []);
                setDefaultModel(settingsRes.data.defaultModel ?? null);
            }
            if (!modelsRes.error && modelsRes.data)
                setModels(modelsRes.data.models ?? []);
            if (!usageRes.error && usageRes.data)
                setUsage(usageRes.data);
        })
            .catch(() => {
            if (!cancelled)
                setLoadError('Failed to load AI settings.');
        })
            .finally(() => {
            if (!cancelled)
                setLoading(false);
        });
        return () => {
            cancelled = true;
        };
    }, [reloadKey]);
    const setDefaultProvider = useCallback((id) => {
        setForm((prev) => ({ ...prev, defaultProviderId: id, defaultModelId: '' }));
        setSaveState('idle');
    }, []);
    const setDefaultModelId = useCallback((id) => {
        setForm((prev) => ({ ...prev, defaultModelId: id }));
        setSaveState('idle');
    }, []);
    const setMonthlyTokenLimit = useCallback((value) => {
        setForm((prev) => ({ ...prev, monthlyTokenLimit: value.replace(/[^\d]/g, '') }));
        setSaveState('idle');
    }, []);
    const toggleFeature = useCallback((key, enabled) => {
        setForm((prev) => ({
            ...prev,
            features: prev.features.map((f) => (f.key === key ? { ...f, enabled } : f)),
        }));
        setSaveState('idle');
    }, []);
    const setFeatureModel = useCallback((key, modelId) => {
        setForm((prev) => ({
            ...prev,
            features: prev.features.map((f) => f.key === key ? { ...f, modelId, providerId: modelId ? f.providerId : '' } : f),
        }));
        setSaveState('idle');
    }, []);
    const setBrandVoice = useCallback((patch) => {
        setForm((prev) => ({ ...prev, brandVoice: { ...prev.brandVoice, ...patch } }));
        setSaveState('idle');
    }, []);
    const budgetError = useMemo(() => {
        if (form.monthlyTokenLimit === '')
            return null;
        const n = Number(form.monthlyTokenLimit);
        if (!Number.isFinite(n) || n < 0)
            return 'Monthly token limit must be a non-negative number.';
        return null;
    }, [form.monthlyTokenLimit]);
    const dirty = useMemo(() => {
        if (form.defaultProviderId !== baseline.defaultProviderId)
            return true;
        if (form.defaultModelId !== baseline.defaultModelId)
            return true;
        if (form.monthlyTokenLimit !== baseline.monthlyTokenLimit)
            return true;
        if (form.features.length !== baseline.features.length)
            return true;
        const bvKeys = [
            'enabled',
            'name',
            'tone',
            'audience',
            'guidelines',
            'sampleText',
        ];
        if (bvKeys.some((k) => form.brandVoice[k] !== baseline.brandVoice[k]))
            return true;
        return form.features.some((f, i) => {
            const base = baseline.features[i];
            return f.enabled !== base?.enabled || (f.modelId ?? '') !== (base?.modelId ?? '');
        });
    }, [form, baseline]);
    const save = useCallback(async () => {
        if (!canEdit || budgetError)
            return;
        setSaveState('saving');
        setSaveError(null);
        try {
            const res = await cmsApi('/ai/settings', {
                method: 'PUT',
                body: JSON.stringify({
                    defaultProviderId: form.defaultProviderId || null,
                    defaultModelId: form.defaultModelId || null,
                    features: form.features.map((f) => ({
                        key: f.key,
                        enabled: f.enabled,
                        modelId: f.modelId ? f.modelId : null,
                    })),
                    budget: {
                        monthlyTokenLimit: form.monthlyTokenLimit === '' ? null : Number(form.monthlyTokenLimit),
                    },
                    brandVoice: brandVoiceIsEmpty(form.brandVoice)
                        ? null
                        : {
                            enabled: form.brandVoice.enabled,
                            name: form.brandVoice.name,
                            tone: form.brandVoice.tone,
                            audience: form.brandVoice.audience,
                            guidelines: form.brandVoice.guidelines,
                            sampleText: form.brandVoice.sampleText,
                        },
                }),
            });
            if (res.error)
                throw new Error(res.error);
            setBaseline(form);
            setSaveState('success');
            // Refresh usage so the budget meter reflects the new limit immediately.
            const usageRes = await cmsApi('/ai/usage/summary');
            if (!usageRes.error && usageRes.data)
                setUsage(usageRes.data);
        }
        catch (err) {
            setSaveState('error');
            setSaveError(err instanceof Error ? err.message : 'Failed to save AI settings.');
        }
    }, [canEdit, budgetError, form]);
    const reset = useCallback(() => {
        setForm(baseline);
        setSaveState('idle');
        setSaveError(null);
    }, [baseline]);
    const refetch = useCallback(() => setReloadKey((k) => k + 1), []);
    const reloadProviders = useCallback(async () => {
        const res = await cmsApi('/ai/settings');
        if (!res.error && res.data) {
            setProviders(res.data.providers ?? []);
            setDefaultModel(res.data.defaultModel ?? null);
        }
    }, []);
    const createProvider = useCallback(async (input) => {
        if (!canEdit)
            return { ok: false, error: 'You do not have permission to do this.' };
        setBusyProviderId('new');
        try {
            const res = await cmsApi('/ai/providers', {
                method: 'POST',
                body: JSON.stringify(input),
            });
            if (res.error)
                return { ok: false, error: res.error };
            await reloadProviders();
            return { ok: true };
        }
        finally {
            setBusyProviderId(null);
        }
    }, [canEdit, reloadProviders]);
    const updateProvider = useCallback(async (id, patch) => {
        if (!canEdit)
            return { ok: false, error: 'You do not have permission to do this.' };
        setBusyProviderId(id);
        try {
            const res = await cmsApi(`/ai/providers/${id}`, {
                method: 'PUT',
                body: JSON.stringify(patch),
            });
            if (res.error)
                return { ok: false, error: res.error };
            await reloadProviders();
            return { ok: true };
        }
        finally {
            setBusyProviderId(null);
        }
    }, [canEdit, reloadProviders]);
    const deleteProvider = useCallback(async (id) => {
        if (!canEdit)
            return { ok: false, error: 'You do not have permission to do this.' };
        setBusyProviderId(id);
        try {
            const res = await cmsApi(`/ai/providers/${id}`, { method: 'DELETE' });
            if (res.error)
                return { ok: false, error: res.error };
            await reloadProviders();
            await loadModels();
            return { ok: true };
        }
        finally {
            setBusyProviderId(null);
        }
    }, [canEdit, reloadProviders, loadModels]);
    const testProvider = useCallback(async (id) => {
        if (!canEdit)
            return { ok: false, error: 'You do not have permission to do this.' };
        setBusyProviderId(id);
        try {
            const res = await cmsApi(`/ai/providers/${id}/test`, { method: 'POST' });
            if (res.error)
                return { ok: false, error: res.error };
            await reloadProviders();
            return {
                ok: res.data?.result.ok ?? false,
                status: res.data?.result.status,
                message: res.data?.result.message,
            };
        }
        finally {
            setBusyProviderId(null);
        }
    }, [canEdit, reloadProviders]);
    const syncModels = useCallback(async (id) => {
        if (!canEdit)
            return { ok: false, error: 'You do not have permission to do this.' };
        setBusyProviderId(id);
        try {
            const res = await cmsApi(`/ai/providers/${id}/sync-models`, { method: 'POST' });
            if (res.error)
                return { ok: false, error: res.error };
            await loadModels();
            await reloadProviders();
            return {
                ok: true,
                fromFallback: res.data?.fromFallback,
                warning: res.data?.warning ?? null,
            };
        }
        finally {
            setBusyProviderId(null);
        }
    }, [canEdit, loadModels, reloadProviders]);
    return {
        loading,
        loadError,
        providers,
        models,
        usage,
        defaultModel,
        form,
        setDefaultProvider,
        setDefaultModel: setDefaultModelId,
        setMonthlyTokenLimit,
        toggleFeature,
        setFeatureModel,
        setBrandVoice,
        dirty,
        budgetError,
        saveState,
        saveError,
        save,
        reset,
        refetch,
        createProvider,
        updateProvider,
        deleteProvider,
        testProvider,
        syncModels,
        busyProviderId,
    };
}
//# sourceMappingURL=useAiSettings.js.map