import * as React from 'react';
import { useState } from 'react';
import StringExtensions from '../../../Utilities/Extensions/StringExtensions';
import { OnePageWizard } from '../../Wizard/OnePageWizards';
import { ConfigurationWizardColumnsStep } from './ConfigurationWizardColumnsStep';
import GridOptionsForm from './GridOptionsForm';
import EntitlementsForm from './EntitlementsForm';
import { UIElementsForm } from './UIOptions/UiOptionsForm';
import { AdaptableOptionsForm } from './AdaptableOptionsForm';
import { applyDefaultAdaptableOptions } from '../../../AdaptableOptions/DefaultAdaptableOptions';
export const ConfigurationWizard = (props) => {
    const [isPrimaryKeySelected, setIsValid] = React.useState(true);
    const [adaptableConfig, setAdaptableConfig] = useState(() => {
        const gridOptionDefaults = {
            sideBar: {
                toolPanels: ['columns', 'filters', 'adaptable'],
            },
        };
        const gridOptions = {
            ...gridOptionDefaults,
            ...props.adaptableConfig.gridOptions,
        };
        const adaptableOptions = applyDefaultAdaptableOptions(props.adaptableConfig.adaptableOptions);
        return { gridOptions, adaptableOptions };
    });
    const [selectedColumns, setSelectedColumns] = useState(() => {
        return props.adaptableConfig.gridOptions?.columnDefs?.reduce((acc, col) => {
            acc[col.field] = true;
            return acc;
        }, {});
    });
    const columnsHandle = React.useRef(null);
    const handleFinish = () => {
        const newAdaptableOptions = { ...adaptableConfig.adaptableOptions };
        const newGridOptions = { ...adaptableConfig.gridOptions };
        if (columnsHandle.current) {
            adaptableConfig.gridOptions.columnDefs = columnsHandle.current.getColumns().map((column) => {
                const newColumn = {
                    ...column,
                    headerName: column.caption || StringExtensions.Humanize(column.field),
                };
                delete newColumn.caption;
                return newColumn;
            });
            const columnDefs = adaptableConfig.gridOptions.columnDefs;
            // handle the layout creation
            let Layouts = newAdaptableOptions.initialState?.Layout?.Layouts || [];
            const NewLayout = {
                TableColumns: columnDefs.map((col) => col.colId ?? col.field),
                Name: 'Default Layout',
            };
            let currentLayoutName = NewLayout.Name;
            let found = false;
            if (!Layouts.length) {
                // no layouts, make this the only one
                Layouts = [NewLayout];
            }
            else {
                Layouts = Layouts.map((layout) => {
                    if (found) {
                        return layout;
                    }
                    if (layout.TableColumns?.length === 0) {
                        // when finding the first empty layout
                        // set its column to be those of the new layout
                        found = true;
                        // and grab the name so we can put it in the Layout.CurrentLayout state
                        currentLayoutName = layout.Name;
                        layout = { ...layout };
                        layout.TableColumns = NewLayout.TableColumns;
                    }
                    return layout;
                });
                if (!found) {
                    Layouts.push(NewLayout);
                }
            }
            newAdaptableOptions.initialState = {
                ...newAdaptableOptions.initialState,
                Layout: {
                    ...newAdaptableOptions.initialState.Layout,
                    Layouts: Layouts,
                    CurrentLayout: currentLayoutName,
                },
            };
            newAdaptableOptions.primaryKey = columnsHandle.current.getPrimaryKey();
        }
        const newAdaptableConfig = {
            adaptableOptions: newAdaptableOptions,
            gridOptions: newGridOptions,
        };
        setAdaptableConfig(newAdaptableConfig);
        props.onFinish(newAdaptableConfig);
    };
    const handlePrimaryKeyColumnIsNotSelected = React.useCallback((newIsValid) => {
        setIsValid(newIsValid);
    }, []);
    const handleColumnsChange = React.useCallback((columns) => {
        setAdaptableConfig((adaptableConfig) => ({
            ...adaptableConfig,
            gridOptions: { ...adaptableConfig.gridOptions, columnDefs: columns },
        }));
    }, []);
    const handleColumnSelectionChange = React.useCallback((col, flag) => {
        setSelectedColumns((selectedColumns) => {
            const newSelectedColumns = selectedColumns ?? {};
            newSelectedColumns[col.field] = flag;
            return newSelectedColumns;
        });
    }, []);
    const handleAdaptableOptionsChange = React.useCallback((adaptableOptions) => {
        setAdaptableConfig((adaptableConfig) => ({
            ...adaptableConfig,
            adaptableOptions: adaptableOptions,
        }));
    }, []);
    const handleGridOptionsChange = React.useCallback((gridOptions) => {
        setAdaptableConfig((adaptableConfig) => ({
            ...adaptableConfig,
            gridOptions: gridOptions,
        }));
    }, []);
    let sections = [
        {
            title: 'Columns',
            details: 'Configure Columns',
            isValid: () => {
                if (!isPrimaryKeySelected) {
                    return 'Primary key column must be included';
                }
                return true;
            },
            render: () => (React.createElement(ConfigurationWizardColumnsStep, { adaptableConfig: adaptableConfig, setPrimaryKeyIsNotSelected: handlePrimaryKeyColumnIsNotSelected, onChange: setAdaptableConfig, selectedColumns: selectedColumns, onSelectionChange: handleColumnSelectionChange, onColumnChange: handleColumnsChange, columnsHandle: columnsHandle })),
        },
        {
            title: 'AdapTable Options',
            details: 'Configure Adaptable Options',
            isValid: () => adaptableConfig.adaptableOptions.adaptableId ? true : 'Adaptable ID is required',
            render: () => (React.createElement(AdaptableOptionsForm, { adaptableOptions: adaptableConfig.adaptableOptions, onChangedAdaptableOptions: handleAdaptableOptionsChange })),
        },
        {
            title: 'AG Grid Options',
            details: 'Configure AG Grid Options',
            render: () => (React.createElement(GridOptionsForm, { gridOptions: adaptableConfig.gridOptions, onChangedGridOptions: handleGridOptionsChange })),
        },
        {
            title: 'UI Elements',
            details: 'Configure UI Elements',
            render: () => (React.createElement(UIElementsForm, { adaptableOptions: adaptableConfig.adaptableOptions, gridOptions: adaptableConfig.gridOptions, onChangedAdaptableOptions: handleAdaptableOptionsChange, onChangedGridOptions: handleGridOptionsChange })),
        },
        {
            title: 'Entitlements',
            details: 'Configure Entitlements',
            render: () => (React.createElement(EntitlementsForm, { adaptableOptions: adaptableConfig.adaptableOptions, onChangedAptableOptions: handleAdaptableOptionsChange })),
        },
        /**
        financePlugin && {
          title: 'Finance',
          details: 'Finance Options',
          render: () => (
            <FinanceForm
              adaptableConfig={adaptableConfig}
              onChangedAdaptableConfig={setAdaptableConfig}
            />
          ),
        },  */
    ].filter(Boolean);
    if (props.startSections) {
        sections = [
            ...props.startSections.map((section) => {
                return {
                    title: section.title,
                    isValid: section.isValid,
                    isVisible: section.isVisible,
                    render: () => {
                        return section.render(adaptableConfig, setAdaptableConfig, setSelectedColumns);
                    },
                };
            }),
            ...sections,
        ];
    }
    return (React.createElement(OnePageWizard, { data: adaptableConfig, name: "Configure", defaultCurrentSectionName: 'default section name', onHide: () => null, onFinish: handleFinish, sections: sections }));
};
