/**
 * Settings state for the whole screen.
 *
 * Sections (one per page) arrive from PHP with the option group they save
 * into. Values are kept per group, not per page: like the old single form,
 * "Save Changes" on any general page saves every general option, while the
 * chatbot keeps its own group and button.
 */
import { create } from 'zustand';
import { __ } from '@wordpress/i18n';
import boot from '@/lib/boot';
import { ajax, errorMessage } from '@/lib/api';
import type { GroupKey, Models, OptionValue, OptionValues, SaveMessage, Section, Sections, SettingsState } from '@/types';

type GroupValues = Partial<Record<GroupKey, OptionValues>>;

interface SaveResult {
    ok: boolean;
    messages: SaveMessage[];
}

interface SettingsStore {
    models: Models;
    sections: Sections;
    values: GroupValues;
    saved: GroupValues;
    saving: Partial<Record<GroupKey, boolean>>;
    setValue: ( group: GroupKey, option: string, value: OptionValue ) => void;
    isDirty: ( group: GroupKey ) => boolean;
    applyState: ( state: SettingsState, reset?: GroupKey[] ) => void;
    refresh: () => Promise<void>;
    save: ( group: GroupKey, extra?: OptionValues ) => Promise<SaveResult>;
}

function collectGroupValues( sections: Sections ): GroupValues {
    const groups: GroupValues = {};
    Object.values( sections ).forEach( ( section ) => {
        if ( section.group ) {
            groups[ section.group ] = { ...groups[ section.group ], ...section.values };
        }
    } );
    return groups;
}

/** Compares values the way the form sees them: 60 and "60" are equal. */
function serialize( values: OptionValues | undefined ): string {
    return JSON.stringify( values ?? {}, ( _, value ) => ( 'number' === typeof value ? String( value ) : value ) );
}

const initialValues = collectGroupValues( boot.sections );

export const useSettingsStore = create<SettingsStore>()( ( set, get ) => ( {
    models: boot.models,
    sections: boot.sections,
    values: initialValues,
    saved: initialValues,
    saving: {},

    setValue: ( group, option, value ) =>
        set( ( state ) => ( {
            values: { ...state.values, [ group ]: { ...state.values[ group ], [ option ]: value } },
        } ) ),

    isDirty: ( group ) => serialize( get().values[ group ] ) !== serialize( get().saved[ group ] ),

    /**
     * Swaps in fresh state from PHP. Groups in `reset` (or without unsaved
     * edits) take the saved values; other groups keep what the user typed.
     */
    applyState: ( state, reset = [] ) =>
        set( ( current ) => {
            const fresh  = collectGroupValues( state.sections );
            const values = { ...current.values };

            ( Object.keys( fresh ) as GroupKey[] ).forEach( ( group ) => {
                if ( reset.includes( group ) || ! get().isDirty( group ) ) {
                    values[ group ] = fresh[ group ];
                }
            } );

            return { models: state.models, sections: state.sections, values, saved: fresh };
        } ),

    /** Reloads state after something outside the form changed (e.g. the API key). */
    refresh: async () => {
        const response = await ajax<SettingsState>( 'wtofe_get_settings_state', { nonce: boot.nonce } );
        if ( response?.success && response.data ) {
            get().applyState( response.data );
        }
    },

    /**
     * Saves one option group. `extra` is sent without being kept in the form
     * (the new API key).
     */
    save: async ( group, extra = {} ) => {
        const failed = __( 'Could not save the settings. Please try again.', 'ai-content-generator-for-woocommerce' );
        set( ( state ) => ( { saving: { ...state.saving, [ group ]: true } } ) );

        try {
            const response = await ajax<{ state: SettingsState; messages: SaveMessage[] }>( 'wtofe_save_settings', {
                nonce: boot.nonce,
                group,
                values: JSON.stringify( { ...get().values[ group ], ...extra } ),
            } );

            if ( ! response?.success || ! response.data ) {
                return { ok: false, messages: [ { type: 'error', message: errorMessage( response, failed ) } ] };
            }

            get().applyState( response.data.state, [ group ] );
            return { ok: true, messages: response.data.messages };
        } catch {
            return { ok: false, messages: [ { type: 'error', message: failed } ] };
        } finally {
            set( ( state ) => ( { saving: { ...state.saving, [ group ]: false } } ) );
        }
    },
} ) );

function anyDirty( state: SettingsStore ): boolean {
    return ( Object.keys( state.values ) as GroupKey[] ).some( ( group ) => state.isDirty( group ) );
}

/** Whether any option group has unsaved edits, read once (outside React). */
export function hasUnsavedChanges(): boolean {
    return anyDirty( useSettingsStore.getState() );
}

/** Whether any option group has unsaved edits. */
export function useHasUnsavedChanges(): boolean {
    return useSettingsStore( anyDirty );
}

/**
 * One option's value and setter, for a field component.
 */
export function useOption<T extends OptionValue = OptionValue>( group: GroupKey, option: string ): [ T | undefined, ( next: T ) => void ] {
    const value    = useSettingsStore( ( state ) => state.values[ group ]?.[ option ] ) as T | undefined;
    const setValue = useSettingsStore( ( state ) => state.setValue );
    return [ value, ( next ) => setValue( group, option, next ) ];
}

/** A page's section, with its `data` narrowed by the page. */
export function useSection<TData>( id: string ): Section<TData> | undefined {
    return useSettingsStore( ( state ) => state.sections[ id ] ) as Section<TData> | undefined;
}
