import { AddIcon, DeleteIcon } from '@fluentui/react-icons';
import { makeStyles } from '@material-ui/core';
import React, { useCallback, useState } from 'react';
import { FieldArray } from 'react-final-form-arrays';
import { useTranslation } from 'react-i18next';
import SearchSideSheet from './SearchSideSheet';
import AutocompleteFinalField from './AutocompleteFinalField';
import DateRangeField from './DateRangeField';
import { FieldType } from './fieldArrayCardEnum';
import { AmbientCard } from '../../surfaces/cards/AmbientCard';
import { DateTimeField } from '../datetimes/DateTimeField';
import { EmptyStateDisplay } from '../../dataDisplay/EmptyStateDisplay';
import { Field } from '../../../utilities/form';
import { FluentCheckbox } from '../checkbox/FluentCheckbox';
import { FluentDatePicker } from '../pickers/FluentDatePicker';
import { FluentTextField } from '../textField/FluentTextField';
import { FluentTimePicker } from '../pickers/FluentTimePicker';
import { FluentToggle } from '../toggle/FluentToggle';
import { FormControlLabel } from '../../utilityDisplay/FormControlLabel';
import { Grid } from '../../Grid';
import { IconButtonWithTooltip } from '../buttons/IconButtonWithToolTip';
import { LayoutUnit } from '../../../layout/LayoutUnit';
import { Typography } from '../../dataDisplay/typography/Typography';
const useStyles = makeStyles(theme => ({
    toggleWrapper: {
        marginLeft: theme.spacing(-0.1),
        gap: theme.spacing(1),
        marginTop: theme.spacing(0.8),
    },
    checkboxField: {
        marginLeft: theme.spacing(-1.1),
    },
    sectionHeader: {
        display: 'flex',
        justifyContent: 'space-between',
        gap: theme.spacing(1),
        alignItems: 'center',
        marginBottom: theme.spacing(1),
    },
    fieldsWrapper: {
        display: 'flex',
        flexDirection: 'column',
    },
    cardsWrapper: {
        display: 'flex',
        flexDirection: 'column',
        gap: theme.spacing(2),
    },
    cardHeader: {
        display: 'flex',
        justifyContent: 'space-between',
        gap: theme.spacing(1),
        alignItems: 'center',
    },
}));
export const FieldArrayCard = props => {
    const { title = ' ', fieldArrayName, getRowTitle, fieldConfig, removeTopLayoutUnit = false, defaultAddedItemValues, 
    //search sidesheet props
    enableSearchSideSheet, searchSideSheetTitle, searchFieldId = 'id', formFieldId = 'id', formatAddedSearchItems, productApiBase, searchApi, searchGridColDefs, searchGridTitle, handleSearch, disableExcludeInSearch = false, searchSideSheetWidth, searchSideSheetHeight, } = props;
    const classes = useStyles();
    const [openSideSheet, setOpenSideSheet] = useState(false);
    const { t } = useTranslation();
    const getField = useCallback((finalFieldName, config, fieldObj) => {
        const { fieldName, fieldType, fieldLabel, componentProps } = config;
        let fieldComponent = null;
        switch (fieldType) {
            case FieldType.DropdownMenu:
                fieldComponent = (React.createElement(Field, Object.assign({}, componentProps, { name: `${finalFieldName}.${fieldName}`, component: AutocompleteFinalField, label: fieldLabel })));
                break;
            case FieldType.Date:
                fieldComponent = (React.createElement(Field, Object.assign({}, componentProps, { name: `${finalFieldName}.${fieldName}`, component: FluentDatePicker, label: fieldLabel, size: "small", allowNull: true })));
                break;
            case FieldType.DateRange:
                fieldComponent = (React.createElement(DateRangeField, Object.assign({}, componentProps, { fieldName: finalFieldName, initialValues: fieldObj })));
                break;
            case FieldType.Time:
                fieldComponent = (React.createElement(Field, Object.assign({}, componentProps, { name: `${finalFieldName}.${fieldName}`, component: FluentTimePicker, label: fieldLabel, size: "small" })));
                break;
            case FieldType.DateTime:
                fieldComponent = (React.createElement(Field, Object.assign({}, componentProps, { name: `${finalFieldName}.${fieldName}`, component: DateTimeField, label: fieldLabel, size: "small", allowNull: true })));
                break;
            case FieldType.Toggle:
                fieldComponent = (React.createElement(FormControlLabel, { control: React.createElement(Field, Object.assign({ defaultChecked: false }, componentProps, { name: `${finalFieldName}.${fieldName}`, component: FluentToggle, type: "checkbox" })), label: fieldLabel, className: classes.toggleWrapper }));
                break;
            case FieldType.Checkbox:
                fieldComponent = (React.createElement(FormControlLabel, { control: React.createElement(Field, Object.assign({ defaultChecked: false }, componentProps, { name: `${finalFieldName}.${fieldName}`, component: FluentCheckbox, type: "checkbox" })), label: fieldLabel, className: classes.checkboxField }));
                break;
            default:
                fieldComponent = (React.createElement(Field, Object.assign({}, componentProps, { name: `${finalFieldName}.${fieldName}`, component: FluentTextField, label: fieldLabel })));
                break;
        }
        return fieldComponent;
    }, [classes.checkboxField, classes.toggleWrapper]);
    const handleCloseSideSheet = useCallback((selectedRecords, fieldArray) => {
        var _a;
        const formattedRecords = formatAddedSearchItems
            ? formatAddedSearchItems(selectedRecords !== null && selectedRecords !== void 0 ? selectedRecords : [])
            : selectedRecords;
        if (formattedRecords === null || formattedRecords === void 0 ? void 0 : formattedRecords.length) {
            for (const record of formattedRecords) {
                if (disableExcludeInSearch ||
                    !!!((_a = fieldArray === null || fieldArray === void 0 ? void 0 : fieldArray.value) === null || _a === void 0 ? void 0 : _a.find(item => item[formFieldId] === record[formFieldId])))
                    fieldArray.push(record);
            }
        }
        setOpenSideSheet(false);
    }, [disableExcludeInSearch, formFieldId, formatAddedSearchItems]);
    const handleAddField = useCallback(fields => {
        if (enableSearchSideSheet) {
            setOpenSideSheet(true);
        }
        else {
            if (defaultAddedItemValues) {
                fields.push(defaultAddedItemValues);
            }
            else {
                fields.push({});
            }
        }
    }, [defaultAddedItemValues, enableSearchSideSheet]);
    return (React.createElement("div", null, React.createElement(FieldArray, { name: fieldArrayName }, ({ fields }) => {
        var _a;
        return (React.createElement("div", null, React.createElement("div", { className: classes.sectionHeader }, React.createElement("div", null, title && React.createElement(Typography, { variant: "h6" }, title)), React.createElement(IconButtonWithTooltip, { onClick: () => {
                handleAddField(fields);
            }, icon: AddIcon, title: t('Add') })), React.createElement("div", { className: classes.cardsWrapper }, ((_a = fields === null || fields === void 0 ? void 0 : fields.value) === null || _a === void 0 ? void 0 : _a.length) > 0 ? (fields.map((name, index) => {
            var _a;
            const rowTitle = getRowTitle && getRowTitle((_a = fields === null || fields === void 0 ? void 0 : fields.value) === null || _a === void 0 ? void 0 : _a[index]);
            return (React.createElement(AmbientCard, { fullWidth: true }, React.createElement("div", { className: classes.cardHeader }, React.createElement(Typography, { variant: "h6" }, rowTitle), React.createElement(IconButtonWithTooltip, { onClick: () => fields.remove(index), icon: DeleteIcon, title: t('Delete') })), rowTitle && !removeTopLayoutUnit && (React.createElement(LayoutUnit, { unit: "xxs" })), React.createElement("div", { className: classes.fieldsWrapper }, fieldConfig === null || fieldConfig === void 0 ? void 0 : fieldConfig.map(config => {
                var _a;
                if (Array.isArray(config)) {
                    return (React.createElement(Grid, { container: true, spacing: 2 }, config === null || config === void 0 ? void 0 : config.map(innerConfig => {
                        var _a;
                        return (React.createElement(Grid, { item: true, xs: 12, sm: 12 / (config === null || config === void 0 ? void 0 : config.length) }, getField(name, innerConfig, (_a = fields === null || fields === void 0 ? void 0 : fields.value) === null || _a === void 0 ? void 0 : _a[index])));
                    })));
                }
                else {
                    return getField(name, config, (_a = fields === null || fields === void 0 ? void 0 : fields.value) === null || _a === void 0 ? void 0 : _a[index]);
                }
            }))));
        })) : (React.createElement(AmbientCard, { fullWidth: true, cardHeight: "155px" }, React.createElement(EmptyStateDisplay, { primaryText: t('No records to show'), secondaryText: t('Try adding one') })))), React.createElement(SearchSideSheet, { open: openSideSheet, handleClose: data => {
                handleCloseSideSheet(data, fields);
            }, exclude: disableExcludeInSearch ? [] : fields === null || fields === void 0 ? void 0 : fields.value, title: searchSideSheetTitle, productApiBase: productApiBase, searchApi: searchApi, colDefs: searchGridColDefs, idField: searchFieldId, formIdField: formFieldId, gridTitle: searchGridTitle, handleSearch: handleSearch, width: searchSideSheetWidth, height: searchSideSheetHeight })));
    })));
};
//# sourceMappingURL=FieldArrayCard.js.map