import React, { useEffect, useState, useCallback, useRef } from 'react';
import { __ } from '@wordpress/i18n';

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

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

// helpers
import getQueryParamsForPaginatedEndpoint from '../../../../helpers/getQueryParamsForPaginatedEndpoint';

// components
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { Button } from 'primereact/button';
import { Dialog } from 'primereact/dialog';
import { InputText } from 'primereact/inputtext';
import { Toast } from 'primereact/toast';

const statuses = [
    'SUBMIT', 'EVALUATION', 'SOCCORSO', 'APPOINTMENT', 'NDG', 'ADMISSIBLE',
    'AWAITING_TECHNICAL_EVALUATION', 'TECHNICAL_EVALUATION'
];

const ManageNdgSection = () => {
    const [localAsyncRequest, setLocalAsyncRequest] = useState(false);
    const [items, setItems] = useState(null);
    const [totalRecordsNum, setTotalRecordsNum] = useState(0);
    const [isNdgDialogVisible, setIsNdgDialogVisible] = useState(false);
    const [selectedAppId, setSelectedAppId] = useState(null);
    const [ndgValue, setNdgValue] = useState('');
    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' }
        }
    });
    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 } = resp.data;
            setTotalRecordsNum(totalRecords);
            setItems(body);
        }
        setLocalAsyncRequest(false);
    };

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

    const openNdgDialog = (appId) => {
        setSelectedAppId(appId);
        setNdgValue('');
        setIsNdgDialogVisible(true);
    };

    const hideNdgDialog = () => {
        setIsNdgDialogVisible(false);
        setSelectedAppId(null);
        setNdgValue('');
    };

    const handleSetNdg = useCallback(() => {
        setLocalAsyncRequest(true);
        const body = { application_id: selectedAppId, ndg: ndgValue };

        AdminService.setApplNdg(body, callback, errCallback);
    }, [ndgValue, selectedAppId]);

    const callback = (resp) => {
        setItems(prev => prev.map(o => {
            return o.id === resp.application_id
                ? {
                    ...o,
                    ndg: resp.ndg
                }
                : o;
        }));
        setLocalAsyncRequest(false);
        hideNdgDialog();
    }

    const errCallback = (resp) => {
        if (toast.current) {
            toast.current.show({
                severity: 'error',
                summary: '',
                detail: resp.detail
            });
        }
        setLocalAsyncRequest(false);
        hideNdgDialog();
    }

    const actionsBodyTemplate = (rowData) => {
        return (
            <div className="appPageSection__tableActions lessGap">
                <Button
                    severity="info"
                    onClick={() => openNdgDialog(rowData.id)}
                    label={__('Set NDG', 'gepafin')}
                    icon="pi pi-pencil"
                    size="small"
                    iconPos="right"/>
            </div>
        );
    };

    const clearFilter = () => {
        setLazyState({
            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' }
            }
        });
    };

    const renderHeader = () => (
        <div className="flex justify-content-between">
            <Button type="button" icon="pi pi-filter-slash" label={__('Pulisci', 'gepafin')} outlined
                    onClick={clearFilter}/>
        </div>
    );

    const ndgDialogFooter = (
        <div>
            <Button label={__('Annulla', 'gepafin')} icon="pi pi-times" outlined onClick={hideNdgDialog}/>
            <Button label={__('Salva', 'gepafin')} icon="pi pi-check" onClick={handleSetNdg}/>
        </div>
    );

    const header = renderHeader();

    useEffect(() => {
        setLocalAsyncRequest(true);
        const paginationQuery = getPaginationQuery();
        ApplicationService.getApplicationsPaginated(paginationQuery, getCallback, errGetCallback);
    }, [lazyState]);

    return (
        <div className="appPageSection">
            <h2>{__('Gestione NDG', 'gepafin')}</h2>
            <Toast ref={toast}/>
            <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}
                    header={header}
                    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="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 field="ndg" header={__('NDG', 'gepafin')}
                            style={{ minWidth: '8rem' }}/>
                    <Column header={__('Azioni', 'gepafin')}
                            body={actionsBodyTemplate}/>
                </DataTable>
            </div>

            <Dialog
                visible={isNdgDialogVisible}
                modal
                header={__('Imposta NDG', 'gepafin')}
                footer={ndgDialogFooter}
                style={{ maxWidth: '500px', width: '100%' }}
                onHide={hideNdgDialog}>
                <div className="appForm__field">
                    <label htmlFor="ndgInput">{__('NDG', 'gepafin')}</label>
                    <InputText
                        id="ndgInput"
                        value={ndgValue}
                        onChange={(e) => setNdgValue(e.target.value)}
                        placeholder={__('Inserisci NDG', 'gepafin')}
                        style={{ width: '100%' }}/>
                </div>
            </Dialog>
        </div>
    );
};

export default ManageNdgSection;
