import React, { useState, useEffect} from 'react';
import { __, sprintf } from '@wordpress/i18n';
import { is, uniq, isNil, isEmpty, head } from 'ramda';
import { wrap } from 'object-path-immutable';
import { useNavigate } from 'react-router-dom';

// store
import { storeGet, storeSet, useStoreValue } from '../../../../store';

// tools
import getBandoSeverity from '../../../../helpers/getBandoSeverity';
import getBandoLabel from '../../../../helpers/getBandoLabel';
import getDateFromISOstring from '../../../../helpers/getDateFromISOstring';
import set404FromErrorResponse from '../../../../helpers/set404FromErrorResponse';
import getNumberWithCurrency from '../../../../helpers/getNumberWithCurrency';
import renderHtmlContent from '../../../../helpers/renderHtmlContent';

// api
import BandoService from '../../../../service/bando-service';
import PreferredBandoService from '../../../../service/preferred-bando-service';

// components
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { Dropdown } from 'primereact/dropdown';
import { Tag } from 'primereact/tag';
import ProperBandoLabel from '../../../../components/ProperBandoLabel';
import { Button } from 'primereact/button';

// i18n
import translationStrings from '../../../../translationStringsForComponents';
import isDateTimeInPast from '../../../../helpers/isDateTimeInPast';
import isDateTimeInFuture from '../../../../helpers/isDateTimeInFuture';
import { Badge } from 'primereact/badge';

const REACT_APP_HUB_ID = process.env.REACT_APP_HUB_ID;

const AllBandiAccordion = ({ showOnlyPreferred = false, isAntiMoneylaundry = false }) => {
    const chosenCompanyId = useStoreValue('chosenCompanyId');
    const antiMoneyLaundryCalls = useStoreValue('antiMoneyLaundryCalls');
    const companies = useStoreValue('companies');
    const isAsyncRequest = useStoreValue('isAsyncRequest');
    const [items, setItems] = useState([]);
    const [filters, setFilters] = useState(null);
    const [expandedRows, setExpandedRows] = useState(null);
    const [statuses, setStatuses] = useState([]);
    const navigate = useNavigate();
    let filteredItems = items;
    if (REACT_APP_HUB_ID !== 't7jh5wfg9QXylNaTZkPoE') {
        filteredItems = isAntiMoneylaundry
            ? items.filter(o => antiMoneyLaundryCalls.includes(o.id))
            : items.filter(o => !antiMoneyLaundryCalls.includes(o.id));
    }

    useEffect(() => {
        const existingCompany = head(companies.filter(o => o.id === chosenCompanyId));

        if (existingCompany && !isAsyncRequest) {
            storeSet('setAsyncRequest');
            const role = storeGet('getRole')

            if (role === 'ROLE_CONFIDI') {
                BandoService.getBandi(getCallback, errGetCallbacks, [
                    ['companyId', chosenCompanyId],
                    ['onlyPreferredCall', showOnlyPreferred],
                    ['onlyConfidiCall', true]
                ]);
            } else {
                BandoService.getBandi(getCallback, errGetCallbacks, [
                    ['companyId', chosenCompanyId],
                    ['onlyPreferredCall', showOnlyPreferred]
                ]);
            }
        }
    }, [chosenCompanyId, companies]);

    const getCallback = (data) => {
        if (data.status === 'SUCCESS') {
            setItems(getFormattedBandiData(data.data));
            setStatuses(uniq(data.data.map(o => o.status)))
        }
        storeSet('unsetAsyncRequest');
    }

    const errGetCallbacks = (data) => {
        set404FromErrorResponse(data);
        storeSet('unsetAsyncRequest');
    }

    const getFormattedBandiData = (data) => {
        return data.map((d) => {
            d.dates = d.dates.map(v => is(String, v) ? new Date(v) : (v ? v : ''));
            return d;
        });
    };

    const nameBodyTemplate = (rowData) => {
        return <span
            className="appPageSection__titleClickable"
            onClick={() => {
                let newExpandedRows;
                if (isNil(expandedRows) || isNil(expandedRows[rowData.id])) {
                    newExpandedRows = isNil(expandedRows)
                        ? wrap({}).set([rowData.id], true).value()
                        : wrap(expandedRows).set([rowData.id], true).value();
                } else {
                    newExpandedRows = wrap(expandedRows).del([rowData.id]).value();
                }
                setExpandedRows(newExpandedRows);
            }}>{rowData.name}</span>
    }

    const amountBodyTemplate = (rowData) => {
        return <span
            className="appPageSection__titleClickable"
            onClick={() => {
                let newExpandedRows;
                if (isNil(expandedRows) || isNil(expandedRows[rowData.id])) {
                    newExpandedRows = isNil(expandedRows)
                        ? wrap({}).set([rowData.id], true).value()
                        : wrap(expandedRows).set([rowData.id], true).value();
                } else {
                    newExpandedRows = wrap(expandedRows).del([rowData.id]).value();
                }
                setExpandedRows(newExpandedRows);
            }}>{getNumberWithCurrency(rowData.amount)}</span>;
    };

    const statusBodyTemplate = (rowData) => {
        return <ProperBandoLabel status={rowData.status}/>;
    };

    const statusFilterTemplate = (options) => {
        return <Dropdown value={options.value} options={statuses}
                         valueTemplate={getBandoLabel(options.value)}
                         onChange={(e) => options.filterCallback(e.value, options.index)}
                         itemTemplate={statusItemTemplate} placeholder={translationStrings.selectOneLabel} className="p-column-filter"/>;
    };

    const statusItemTemplate = (option) => {
        return <Tag value={getBandoLabel(option)} severity={getBandoSeverity(option)}/>;
    };

    const addToFavourites = (id, preferredId) => {
        const companyId = storeGet('chosenCompanyId')
        const data = {
            companyId,
            callId: id
        }
        if (preferredId && preferredId !== 0) {
            PreferredBandoService.deleteFromPreferred(preferredId, (data) => removeFavCallback(data, id), errToggleFavCallback);
        } else {
            PreferredBandoService.addToPreferred(data, addFavCallback, errToggleFavCallback);
        }
    }

    const removeFavCallback = (data, id) => {
        if (data.status === 'SUCCESS') {
            const newItems = items.map((o) => {
                if (o.id === id) {
                    return {
                        ...o,
                        preferredCallId: null
                    }
                } else {
                    return o;
                }
            });
            setItems(newItems)
        }
    }
    const addFavCallback = (data) => {
        if (data.status === 'SUCCESS') {
            const newItems = items.map((o) => {
                if (o.id === data.data.callId) {
                    return {
                        ...o,
                        preferredCallId: data.data.id
                    }
                } else {
                    return o;
                }
            });
            setItems(newItems)
        }
    }

    const errToggleFavCallback = (data) => {
        set404FromErrorResponse(data);
    }

    const goToBandoPage = (id) => {
        navigate(`/bandi/${id}`)
    }

    const actionsBodyTemplate = (rowData) => {
        return <div className="appPageSection__tableActions">
            <button type="button"
                    className="appPageSection__addToFavourites"
                    data-active={!isNil(rowData.preferredCallId)}
                    onClick={() => addToFavourites(rowData.id, rowData.preferredCallId)}>
                <i className="pi pi-heart" style={{ fontSize: '1rem' }}></i>
            </button>
        </div>
    }

    const rowExpansionTemplate = (data) => {
        const isCallExpired = isDateTimeInPast(data.dates[1], data.endTime);
        const isCallScheduled = isDateTimeInFuture(data.dates[0], data.startTime);

        return (
            <div className="p-3">
                {renderHtmlContent(data.descriptionShort)}
                <p>{__('Scadenza', 'gepafin')}: {getDateFromISOstring(data.dates[1])}</p>
                {!isCallExpired && !isCallScheduled && !isEmpty(chosenCompanyId) && chosenCompanyId !== 0 && (!data.confidi
                || (data.confidi && data.id === 6 && REACT_APP_HUB_ID === 'p4lk3bcx1RStqTaIVVbXs'))
                    ? <Button onClick={() => goToBandoPage(data.id)} severity="info">
                    {isAntiMoneylaundry ? __('Compila', 'gepafin') : __('Partecipa', 'gepafin')}
                </Button> : null}
                {isCallExpired
                    ? <p><Badge value={__('È scaduto', 'gepafin')} severity="danger"></Badge></p> : null}
                {isCallScheduled
                    ? <p><Badge value={sprintf(__('È programmato. Inizia: %s %s', 'gepafin'), getDateFromISOstring(data.dates[0]), data.startTime)}></Badge></p> : null}
                {isCallExpired || isCallScheduled || (!isEmpty(chosenCompanyId) && chosenCompanyId !== 0 && data.confidi
                && (data.id !== 6 || (data.id === 6 && REACT_APP_HUB_ID !== 'p4lk3bcx1RStqTaIVVbXs')))
                    ? <Button onClick={() => goToBandoPage(data.id)} severity="info">
                        {data.allowMultipleApplications
                            ? isAntiMoneylaundry ? __('Compila', 'gepafin') : __('Partecipa', 'gepafin')
                            : __('Mostra', 'gepafin')}
                    </Button> : null}
            </div>
        );
    };

    const allowExpansion = (rowData) => {
        return true;
    };

    return(
        <div className="appPageSection__table">
            <DataTable value={filteredItems}
                       paginator
                       rows={5}
                       loading={isAsyncRequest}
                       dataKey="id"
                       filters={filters}
                       emptyMessage={translationStrings.emptyMessage}
                       expandedRows={expandedRows}
                       onRowToggle={(e) => setExpandedRows(e.data)}
                       rowExpansionTemplate={rowExpansionTemplate}
                       onFilter={(e) => setFilters(e.filters)}>
                <Column expander={allowExpansion} style={{ width: '5rem' }} />
                <Column field="name" header={__('Bando', 'gepafin')}
                        body={nameBodyTemplate}
                        style={{ minWidth: '12rem' }}/>
                {!isAntiMoneylaundry
                    ? <Column header={__('Importo totale', 'gepafin')} filterField="amount"
                        style={{ minWidth: '10rem' }} body={amountBodyTemplate}/>
                    : null}
                <Column field="status" header={__('Stato', 'gepafin')} filterMenuStyle={{ width: '14rem' }}
                        style={{ width: '8rem' }} body={statusBodyTemplate} filter sortable
                        filterElement={statusFilterTemplate}/>
                {!isEmpty(chosenCompanyId) && chosenCompanyId !== 0
                    ? <Column header={__('Azioni', 'gepafin')}
                        style={{ width: '8rem' }}
                        body={actionsBodyTemplate}/> : null}
            </DataTable>
        </div>
    )
}

export default AllBandiAccordion;
