import React, { useEffect, useState, useCallback, useRef } from 'react';
import { __ } from '@wordpress/i18n';
import { is, isEmpty } from 'ramda';
import { Link } from 'react-router-dom';

import translationStrings from '../../../../translationStringsForComponents';

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

// api
import ApplicationService from '../../../../service/application-service';

//
import getBandoLabel from '../../../../helpers/getBandoLabel';
import getBandoSeverity from '../../../../helpers/getBandoSeverity';
import getFormattedDateString from '../../../../helpers/getFormattedDateString';
import getQueryParamsForPaginatedEndpoint from '../../../../helpers/getQueryParamsForPaginatedEndpoint';

// components
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { Button } from 'primereact/button';
import ProperBandoLabel from '../../../../components/ProperBandoLabel';
import { Dropdown } from 'primereact/dropdown';
import { Tag } from 'primereact/tag';
import { Calendar } from 'primereact/calendar';
import { Toast } from 'primereact/toast';
import { classNames } from 'primereact/utils';
import { FileUpload } from 'primereact/fileupload';
import { defaultMaxFileSize } from '../../../../configData';
import getFormatedFileSizeText from '../../../../helpers/getFormatedFileSizeText';
import { Dialog } from 'primereact/dialog';
import { wrap } from 'object-path-immutable';
import ApplicationContractService from '../../../../service/application-contract-service';
import set404FromErrorResponse from '../../../../helpers/set404FromErrorResponse';

const AllDomandeBeneficiarioTableAsync = ({ statuses }) => {
    const isAsyncRequest = useStoreValue('isAsyncRequest');
    const chosenCompanyId = useStoreValue('chosenCompanyId');
    const companies = useStoreValue('companies');
    const [localAsyncRequest, setLocalAsyncRequest] = useState(false);
    const [items, setItems] = useState(null);
    const [totalRecordsNum, setTotalRecordsNum] = useState(0);
    const [lazyState, setLazyState] = useState({
        first: 0,
        rows: 5,
        page: 0,
        sortField: null,
        sortOrder: null,
        filters: {
            id: { value: null, matchMode: 'equals' },
            callTitle: { value: null, matchMode: 'contains' },
            companyName: { value: null, matchMode: 'contains' },
            submissionDate: { value: null, matchMode: 'dateIs' },
            assignedUserName: { value: null, matchMode: 'equals' },
            applicationStatus: { value: null, matchMode: 'equals' }
        }
    });
    const [isVisibleContractForm, setIsVisibleContractForm] = useState(false);
    const [contractFormData, setContractFormData] = useState({
        subject: '',
        text: ''
    });
    const contractFormFilesRef = useRef(null);
    const toast = useRef(null);

    const getPaginationQuery = useCallback(() => getQueryParamsForPaginatedEndpoint(lazyState, statuses, 'id'), [lazyState]);

    const onPage = (event) => {
        setLazyState(event);
    };

    const onSort = (event) => {
        event['first'] = 0;
        event['page'] = 0;
        setLazyState(event);
    };

    const onFilter = useCallback((event) => {
        event['first'] = 0;
        event['page'] = 0;
        setLazyState(event);
    }, [lazyState]);

    const getCallback = (resp) => {
        if (resp.status === 'SUCCESS') {
            const {
                body, totalRecords,
                //currentPage, totalPages, pageSize
            } = resp.data;
            setTotalRecordsNum(totalRecords);
            setItems(getFormattedData(body));
        }
        setLocalAsyncRequest(false);
    }

    const errGetCallbacks = () => {
        setLocalAsyncRequest(false);
    }

    const getFormattedData = (data) => {
        return data.map((d) => {
            d.callEndDate = is(String, d.callEndDate) ? new Date(d.callEndDate) : (d.callEndDate ? d.callEndDate : '');
            d.modifiedDate = is(String, d.modifiedDate) ? new Date(d.modifiedDate) : (d.modifiedDate ? d.modifiedDate : '');
            d.submissionDate = is(String, d.submissionDate) ? new Date(d.submissionDate) : (d.submissionDate ? d.submissionDate : '');
            return d;
        });
    };

    const actionsBodyTemplate = (rowData) => {
        return <div className="appPageSection__tableActions">
            {['SOCCORSO', 'AWAITING_TECHNICAL_EVALUATION'].includes(rowData.status)
                ? <Link to={`/domande/${rowData.id}`}>
                    <Button severity="info" label={__('Dettagli', 'gepafin')} icon="pi pi-eye" size="small"
                            iconPos="right"/>
                </Link> : null}
            <Link to={`/domande/${rowData.id}/preview`}>
                <Button severity="info" label={__('Anteprima', 'gepafin')} icon="pi pi-eye" size="small"
                        iconPos="right"/>
            </Link>
            {rowData.status === 'APPROVED'
                ? <Button severity="success"
                          label={__('Invia contratto firmato', 'gepafin')}
                          icon="pi pi-upload" size="small"
                          iconPos="right" onClick={() => {
                    openSendContractForm();
                }}/>
                : null}
        </div>
    }

    const progressBodyTemplate = () => {
        return '-';
    };

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

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

    const statusFilterTemplate = (options) => {
        return <Dropdown value={options.value} options={statuses}
                         valueTemplate={getBandoLabel(options.value)}
                         onChange={(e) => {
                             options.filterCallback(e.value, options.index)
                             const filters = { ...lazyState.filters };
                             if (e.value) {
                                 filters['applicationStatus'] = { value: e.value, matchMode: 'equals' };
                             } else {
                                 delete filters['applicationStatus'];
                             }
                             setLazyState({ ...lazyState, filters, first: 0 });
                         }}
                         itemTemplate={statusItemTemplate} placeholder={translationStrings.selectOneLabel}
                         className="p-column-filter"/>;
    };

    const dateFilterTemplate = (options) => {
        return <Calendar value={options.value} onChange={(e) => options.filterCallback(e.value, options.index)}
                         dateFormat="dd/mm/yy" placeholder="dd/mm/yyyy" mask="99/99/9999"/>;
    };

    const dateAppliedBodyTemplate = (rowData) => {
        return getFormattedDateString(rowData.submissionDate);
    };

    const openSendContractForm = () => {
        setContractFormData({
            subject: '',
            text: ''
        });
        setIsVisibleContractForm(true);
    };

    const headerContractDialog = () => {
        return <span>{__('Invia il contratto', 'gepafin')}</span>;
    }

    const hideContractDialog = () => {
        setIsVisibleContractForm(false);
        setContractFormData({
            subject: '',
            text: ''
        });
    }

    const footerContractDialog = useCallback(() => {
        let isDisabled = !contractFormData.files || isEmpty(contractFormData.files) || isAsyncRequest;

        return <div>
            <Button type="button" label={__('Annulla', 'gepafin')} onClick={hideContractDialog} outlined/>
            <Button
                type="button"
                disabled={isDisabled}
                label={__('Invia', 'gepafin')} onClick={doSendContract}/>
        </div>
    }, [contractFormData]);

    const updateContractFormData = (value, path) => {
        const newData = wrap(contractFormData).set(path.split('.'), value).value();
        setContractFormData(newData);
    };

    const doSendContract = useCallback(() => {
        if (contractFormData.files && !isEmpty(contractFormData.files) && !isAsyncRequest) {
            const formDataToSend = new FormData();

            if (contractFormData.files && contractFormData.files.length > 0) {
                contractFormData.files.forEach((file) => {
                    formDataToSend.append('beneficiaryContractDocuments', file);
                });
            }

            storeSet('setAsyncRequest');

            ApplicationContractService.updateApplicationContract(
                contractFormData.id,
                formDataToSend,
                getUploadApplicationContractCallback,
                errGetUploadApplicationContractCallback
            );
        }
    }, [contractFormData]);

    const getUploadApplicationContractCallback = (data) => {
        if (data.status === 'SUCCESS') {
            if (toast.current && data.message) {
                toast.current.show({
                    severity: 'success',
                    summary: '',
                    detail: data.message
                });
            }
        }
        hideContractDialog();
        storeSet('unsetAsyncRequest');
    }

    const errGetUploadApplicationContractCallback = (data) => {
        if (toast.current && data.message) {
            toast.current.show({
                severity: data.status === 'SUCCESS' ? 'info' : 'error',
                summary: '',
                detail: data.message
            });
        }
        hideContractDialog();
        set404FromErrorResponse(data);
        storeSet('unsetAsyncRequest');
    }

    useEffect(() => {
        setLocalAsyncRequest(true);
        const paginationQuery = getPaginationQuery();

        ApplicationService.getApplicationsPaginated(paginationQuery, getCallback, errGetCallbacks, [
            ['companyId', chosenCompanyId]
        ]);
    }, [lazyState, chosenCompanyId, companies]);

    return (
        <div className="appPageSection__table">
            <DataTable
                value={items} stripedRows showGridlines
                lazy filterDisplay="menu" dataKey="id" paginator
                first={lazyState.first} rows={lazyState.rows} totalRecords={totalRecordsNum} onPage={onPage}
                onSort={onSort} sortField={lazyState.sortField} sortOrder={lazyState.sortOrder}
                onFilter={onFilter} filters={lazyState.filters} loading={localAsyncRequest}
                emptyMessage={translationStrings.emptyMessage}>
                <Column field="id" header={__('ID domanda', 'gepafin')}
                        sortable
                        filterField="id" filter
                        filterMatchModeOptions={translationStrings.numberFilterOptions}
                        filterPlaceholder={__('Cerca', 'gepafin')}
                        style={{ minWidth: '6rem' }}/>
                <Column field="protocolNumber" header={__('Protocollo', 'gepafin')}
                        style={{ minWidth: '6rem' }}/>
                <Column field="callTitle" header={__('Bando', 'gepafin')}
                        filterField="callTitle" filter
                        filterMatchModeOptions={translationStrings.textFilterOptions}
                        filterPlaceholder={__('Cerca il nome', 'gepafin')}
                        style={{ minWidth: '10rem' }}/>
                <Column field="companyName" header={__('Azienda Beneficiaria', 'gepafin')}
                        filterField="companyName" filter
                        filterMatchModeOptions={translationStrings.textFilterOptions}
                        filterPlaceholder={__('Cerca il nome', 'gepafin')}
                        style={{ minWidth: '8rem' }}/>
                <Column header={__('Data di invio', 'gepafin')}
                        filterElement={dateFilterTemplate} filter
                        filterField="submissionDate" dataType="date"
                        filterMatchModeOptions={translationStrings.dateFilterOptions}
                        style={{ minWidth: '8rem' }}
                        body={dateAppliedBodyTemplate}/>
                <Column field="applicationStatus" header={__('Stato', 'gepafin')}
                        filterElement={statusFilterTemplate} filter
                        filterMatchModeOptions={translationStrings.statusFilterOptions}
                        style={{ minWidth: '8rem' }}
                        body={statusBodyTemplate}/>
                <Column header={__('Esito', 'gepafin')}
                        style={{ minWidth: '7rem' }} field="progress" body={progressBodyTemplate}/>
                <Column header={__('Azioni', 'gepafin')}
                        body={actionsBodyTemplate}/>
            </DataTable>

            <Toast ref={toast}/>

            <Dialog
                visible={isVisibleContractForm}
                modal
                header={headerContractDialog}
                footer={footerContractDialog}
                style={{ maxWidth: '600px', width: '100%' }}
                onHide={hideContractDialog}>
                <div className="appForm__field">
                    <p>Ricarica il contratto formato digitalmente:</p>
                </div>
                <div className="appForm__field">
                    <label
                        className={classNames({ 'p-error': !contractFormData.files || isEmpty(contractFormData.files) })}>
                        {__('Files', 'gepafin')}* (p7m)
                    </label>
                    <FileUpload
                        ref={contractFormFilesRef}
                        name="files[]"
                        multiple
                        accept=".p7m,application/pkcs7-mime,application/x-pkcs7-mime"
                        maxFileSize={defaultMaxFileSize}
                        auto={false}
                        customUpload={true}
                        className={classNames({ 'p-invalid': !contractFormData.files || isEmpty(contractFormData.files) })}
                        onSelect={(e) => {
                            updateContractFormData(e.files, 'files');
                        }}
                        onRemove={(e) => {
                            const updatedFiles = contractFormFilesRef.current.getFiles();
                            updateContractFormData(updatedFiles, 'files');
                        }}
                        headerTemplate={(options) => {
                            const { chooseButton } = options;
                            return (
                                <div className="p-fileupload-buttonbar" data-pc-section="buttonbar">
                                    {chooseButton}
                                </div>
                            );
                        }}
                        chooseOptions={{
                            label: __('Aggiungi i file', 'gepafin'),
                            icon: 'pi pi-plus'
                        }}
                        itemTemplate={(file, props) => {
                            return (
                                <div className="p-fileupload-row" data-pc-section="file">
                                    <div data-pc-section="details" style={{
                                        display: 'flex',
                                        flexDirection: 'column',
                                        gap: '10px',
                                        textAlign: 'left'
                                    }}>
                                        <div className="p-fileupload-filename" data-pc-section="filename">
                                            {file.name}
                                        </div>
                                        <span
                                            data-pc-section="filesize">{getFormatedFileSizeText(file.size)}</span>
                                    </div>
                                    <div data-pc-section="actions">
                                        <Button
                                            type="button"
                                            icon="pi pi-times"
                                            className="p-button-rounded p-button-danger p-button-text"
                                            onClick={() => props.onRemove()}
                                        />
                                    </div>
                                </div>
                            )
                        }}
                        emptyTemplate={<p className="m-0">{__('Trascina i file qua')}</p>}
                    />
                </div>
            </Dialog>
        </div>
    )
}

export default AllDomandeBeneficiarioTableAsync;