import React, { useCallback, useEffect, useState } from 'react';
import { __, sprintf } from '@wordpress/i18n';
import { head, pathOr, pluck } from 'ramda';
import equal from 'fast-deep-equal';

// components
import { InputText } from 'primereact/inputtext';
import { InputSwitch } from 'primereact/inputswitch';

// store
import { storeGet } from '../../../../../../store';

const ElementSettingTableColumnsForCsv = ({ name, setDataFn, value }) => {
    const [stateFieldData, setStateFieldData] = useState([]);
    const canBeEnabled = stateFieldData.filter(o => o.predefined).length > 0;

    const onInputChange = (e, index) => {
        const { value } = e.target;
        const newData = stateFieldData.map((o, i) => {
            if (i === index) {
                o.labelCsv = value;
            }
            return o;
        })
        setStateFieldData(newData);
    }

    const setChecked = (value, index) => {
        //let name = '';
        const newData = stateFieldData.map((o, i) => {
            if (i === index) {
                o.enableCsv = value;
                //name = o.name;
            }
            return o;
        });

        setStateFieldData(newData);
    }

    const properFields = useCallback((item, i) => {
        return <>
            <div>
                <InputText
                    value={item.label}
                    disabled={true}
                    placeholder={sprintf(__('Colonna %d', 'gepafin'), i + 1)}
                    onInput={(e) => onInputChange(e, i)}/>
            </div>
            <div>
                <InputText
                    value={item.labelCsv}
                    disabled={!canBeEnabled}
                    placeholder={item.label}
                    onInput={(e) => onInputChange(e, i)}/>
            </div>
            <div>
                <InputSwitch
                    checked={item.enableCsv}
                    disabled={!canBeEnabled}
                    onChange={(e) => setChecked(e.value, i)}/>
            </div>
        </>
    }, [canBeEnabled]);

    useEffect(() => {
        const settings = storeGet('chosenFieldSettings');
        let newValue = []

        if (settings) {
            const setting = head(settings.filter(o => o.name === 'table_columns'));
            const settingReports = head(settings.filter(o => o.name === 'reportColumns'));
            const settingData = pathOr([], ['value', 'stateFieldData'], setting);
            const settingReportData = pathOr([], ['value'], settingReports);
            const canBeEnabled = settingData.filter(o => o.predefined).length > 0;
            newValue = settingData.map((o) => {
                const existing = pathOr({}, [], head(settingReportData.filter(s => s.name === o.name)));
                const existingEnabled = pathOr(false, ['enableCsv'], existing);
                return {
                    ...o,
                    ...existing,
                    predefined: o.predefined,
                    enableCsv: !canBeEnabled ? false : existingEnabled
                }
            });
        }
        setStateFieldData(newValue);
    }, []);

    useEffect(() => {
        const atLeastOneIsEnabled = pluck('enableCsv', stateFieldData).filter(v => v).length > 0;
        setDataFn(name, stateFieldData);

        if (atLeastOneIsEnabled) {
            setDataFn('reportEnable', true);
        } else {
            setDataFn('reportEnable', false);
        }
    }, [stateFieldData]);

    /*useEffect(() => {
        console.log('value', value, stateFieldData, equal(value, stateFieldData))
        if (!equal(value, stateFieldData)) {
            setStateFieldData(value);
        }
    }, [value]);*/

    return (
        <>
            {!canBeEnabled
                ? <p>{__('Almeno una colonna deve essere predefinita! ⚠️')}</p> : null}
            <div className="formElementSettings__repeater">
                {stateFieldData.length > 0
                    ? <div className="formElementSettings__repeaterItem tableRowCsv">
                        <div>{__('Colonna', 'gepafin')}</div>
                        <div>{__('Header CSV', 'gepafin')}</div>
                        <div>{__('Abilitato?', 'gepafin')}</div>
                    </div> : null}
                {stateFieldData.map((o, i) => <div key={i} className="formElementSettings__repeaterItem tableRowCsv">
                    {properFields(o, i)}
                </div>)}
            </div>
        </>
    )
}

export default ElementSettingTableColumnsForCsv;