import * as React from 'react';
import { useState } from 'react';
import Radio from '../../components/Radio';
import { CheckBox } from '../../components/CheckBox';
import { Tabs } from '../../components/Tabs';
import { SummaryText } from '../Wizard/OnePageAdaptableWizard';
import { NewColumnSelector } from './ColumnSelector';
import { AdaptableFormControlTextClear } from './Forms/AdaptableFormControlTextClear';
import { useAdaptable } from '../AdaptableContext';
import { getColumnTypeFriendlyName } from '../../AdaptableState/Common/AdaptableColumn';
import StringExtensions from '../../Utilities/Extensions/StringExtensions';
import { Box, Flex } from '../../components/Flex';
import { TagList } from '../../components/Tag/Tag';
export const isScopeValid = ({ Scope }) => {
    const result = [];
    if (!Scope) {
        return 'A scope is required.';
    }
    if (Scope && 'ColumnIds' in Scope && Scope.ColumnIds.length === 0) {
        result.push('Please select at least one column for the scope.');
    }
    if (Scope && 'DataTypes' in Scope && Scope.DataTypes.length === 0) {
        result.push('Please select at least one data type for the scope.');
    }
    return result.length ? result.join(', ') : true;
};
const DATA_TYPES_MAP = {
    date: {
        label: 'Date',
        value: 'date',
    },
    number: {
        label: 'Number',
        value: 'number',
    },
    text: {
        label: 'Text',
        value: 'text',
    },
    boolean: {
        label: 'Boolean',
        value: 'boolean',
    },
};
const renderDataTypeLabel = (c) => {
    return 'DataType: ' + StringExtensions.CapitaliseFirstLetter(c);
};
export const renderScopeSummary = (scope, labels) => {
    const adaptable = useAdaptable();
    const scopeApi = adaptable.api.columnScopeApi;
    const columnsInScope = scopeApi.getColumnsInScope(scope);
    return (React.createElement(React.Fragment, null,
        React.createElement(Box, null,
            React.createElement(SummaryText, { className: "twa:mb-0" }, scopeApi.scopeIsAll(scope) ? labels.scopeWholeRow : null)),
        React.createElement(Box, { className: "twa:overflow-hidden" }, 'ColumnIds' in scope ? (React.createElement(React.Fragment, null,
            React.createElement(SummaryText, { className: columnsInScope.length ? 'twa:mb-2' : '' }, labels.scopeColumns),
            columnsInScope.length ? (React.createElement(TagList, { tags: columnsInScope.map((c) => c.friendlyName) })) : null)) : null),
        React.createElement(Box, null, 'DataTypes' in scope ? (React.createElement(React.Fragment, null,
            React.createElement(Box, { className: "twa:text-2 twa:mb-2" }, labels.scopeDataTypes),
            React.createElement(TagList, { tags: scope.DataTypes.map((dataType) => renderDataTypeLabel(dataType)) }))) : null)));
};
const DATA_TYPES_OPTIONS = Object.values(DATA_TYPES_MAP);
export const NewScopeComponent = (props) => {
    const { api } = useAdaptable();
    const { columnScopeApi: scopeApi, columnApi } = api;
    const [columnsSearchText, setColumnsSearchText] = useState('');
    const scopeColumns = React.useMemo(() => {
        const allColumns = props.scopeColumns || columnApi.getUIAvailableColumns();
        if (typeof props.isColumnAvailable === 'function') {
            return allColumns.filter((c) => props.isColumnAvailable(c));
        }
        return allColumns;
    }, []);
    const getTabFromScope = (scope) => {
        if (!scope) {
            return undefined;
        }
        if (scopeApi.scopeIsAll(scope)) {
            return 'Row';
        }
        if (scopeApi.scopeHasColumns(scope)) {
            return 'Column';
        }
        if (scopeApi.scopeHasDataType(scope)) {
            return 'DataType';
        }
        if (scopeApi.scopeHasColumnType(scope)) {
            return 'ColumnType';
        }
        return undefined;
    };
    const [activeTab, setActiveTab] = useState(() => getTabFromScope(props.scope));
    const onTabChanged = (value) => {
        setActiveTab(value);
        if (value === 'Row') {
            props.updateScope({ All: true });
        }
    };
    const onColumnsSelectedChanged = (cols) => {
        const newScope = {
            ColumnIds: cols,
        };
        props.updateScope(newScope);
    };
    const onCheckBoxDataTypeChecked = (checked, item) => {
        let dataTypes = [].concat(scopeApi.getDataTypesInScope(props.scope) ?? []);
        if (checked) {
            dataTypes.push(item);
        }
        else {
            const index = dataTypes.indexOf(item, 0);
            if (index > -1) {
                dataTypes.splice(index, 1);
            }
        }
        let newScope = {
            DataTypes: dataTypes,
        };
        props.updateScope(newScope);
    };
    const dataTypesInScope = props.scope && 'DataTypes' in props.scope ? scopeApi.getDataTypesInScope(props.scope) : null;
    let dataTypeOptions = DATA_TYPES_OPTIONS;
    if (Array.isArray(props.availableDataTypes)) {
        dataTypeOptions = props.availableDataTypes.map((dataType) => DATA_TYPES_MAP[dataType]);
    }
    const hasColumnTypes = React.useMemo(() => {
        return api.columnApi.getColumnTypes()?.length > 0;
    }, []);
    return (React.createElement(Tabs, { "data-name": 'scope-component', className: "ab-ScopeComponent", value: activeTab, style: { height: '100%', ...props.style }, onValueChange: onTabChanged },
        props.hideWholeRow ? null : (React.createElement(Tabs.Tab, { value: "Row" },
            React.createElement(Radio, { className: "twa:m-0", checked: activeTab == 'Row', tabIndex: -1 }, "All Columns"))),
        !props.disableColumns && (React.createElement(Tabs.Tab, { value: "Column" },
            React.createElement(Radio, { className: "twa:m-0", value: "Column", checked: activeTab == 'Column', tabIndex: -1 }, "Selected Columns"))),
        !props.disableDataTypes && (React.createElement(Tabs.Tab, { value: "DataType" },
            React.createElement(Radio, { className: "twa:m-0", value: "DataType", checked: activeTab == 'DataType', tabIndex: -1 }, "Data Types"))),
        hasColumnTypes && (React.createElement(Tabs.Tab, { value: "ColumnType" },
            React.createElement(Radio, { className: "twa:m-0", value: "ColumnType", checked: activeTab == 'ColumnType', tabIndex: -1 }, "Column Types"))),
        props.hideWholeRow ? null : (React.createElement(Tabs.Content, { value: "Row", style: { flex: 'none' }, "data-name": "row-scope" },
            React.createElement(Box, { className: "twa:p-2 twa:pl-0 twa:text-2" }, props.descriptions.rowScope))),
        !props.disableColumns && (React.createElement(Tabs.Content, { value: "Column", "data-name": "column-scope", className: "twa:p-0 twa:flex-1 twa:overflow-auto" },
            React.createElement(Flex, { flexDirection: "row", alignItems: "center", className: "twa:p-2" },
                React.createElement(Box, { className: "twa:text-2" }, props.descriptions.columnScope),
                React.createElement(Box, { className: "twa:flex-3" }),
                React.createElement(AdaptableFormControlTextClear, { value: columnsSearchText, OnTextChange: setColumnsSearchText, placeholder: "Type to search columns", style: { flex: 1 } })),
            React.createElement(Flex, { className: "twa:overflow-hidden twa:pl-2 twa:flex-1" },
                React.createElement(NewColumnSelector, { columnFilterText: columnsSearchText, allowReorder: false, availableColumns: scopeColumns, selected: scopeApi.getColumnIdsInScope(props.scope) ?? [], onChange: onColumnsSelectedChanged })))),
        !props.disableDataTypes && (React.createElement(Tabs.Content, { value: "DataType", style: { flex: 'none' }, "data-name": "datatype-scope" },
            React.createElement(Box, null,
                props.descriptions.dataTypeScope && (React.createElement(Box, { className: "twa:p-2 twa:pl-0 twa:mb-2 twa:text-2" }, props.descriptions.dataTypeScope)),
                React.createElement(Flex, { flexDirection: "column" }, dataTypeOptions.map((dataTypeOption) => (React.createElement(CheckBox, { "data-name": "scope", "data-value": dataTypeOption.value, key: dataTypeOption.value, checked: !!dataTypesInScope && dataTypesInScope.includes(dataTypeOption.value), onChange: (checked) => onCheckBoxDataTypeChecked(checked, dataTypeOption.value) }, dataTypeOption.label))))))),
        hasColumnTypes && (React.createElement(Tabs.Content, { value: "ColumnType", className: "twa:flex-none", "data-name": "column-type-scope" },
            React.createElement(Box, null,
                React.createElement(Flex, { flexDirection: "column" }, api.columnApi.getColumnTypes()?.map?.((columnType) => (React.createElement(CheckBox, { "data-name": "scope", "data-value": columnType, key: columnType, checked: 'ColumnTypes' in props.scope && props.scope.ColumnTypes?.includes(columnType), onChange: (checked) => {
                        let columnTypes = [].concat('ColumnTypes' in props.scope ? props.scope.ColumnTypes : []);
                        if (checked) {
                            columnTypes.push(columnType);
                        }
                        else {
                            columnTypes = columnTypes.filter((ct) => ct !== columnType);
                        }
                        let newScope = {
                            ColumnTypes: columnTypes,
                        };
                        props.updateScope(newScope);
                    } }, getColumnTypeFriendlyName(columnType))))))))));
};
