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

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

// api
import AmendmentsService from '../../../../service/amendments-service';
import AdminService from '../../../../service/admin-service';

// helpers
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 { Dropdown } from 'primereact/dropdown';
import { Tag } from 'primereact/tag';
import { Calendar } from 'primereact/calendar';
import { Toast } from 'primereact/toast';
import ProperBandoLabel from '../../../../components/ProperBandoLabel';

const statuses = ['AWAITING', 'RESPONSE_RECEIVED', 'CLOSE', 'EXPIRED'];

const ManageAmendmentReopenSection = () => {
    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: {
            applicationId: { value: null, matchMode: 'equals' },
            callName: { value: null, matchMode: 'contains' },
            companyName: { value: null, matchMode: 'contains' },
            startDate: { value: null, matchMode: 'dateIs' },
            expirationDate: { value: null, matchMode: 'dateIs' },
            status: { value: null, matchMode: 'equals' }
        }
    });
    const toast = useRef(null);

    const getPaginationQuery = useCallback(
        () => getQueryParamsForPaginatedEndpoint(lazyState, statuses, 'applicationId', { personalRecords: false }),
        [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 getFormattedData = (data) => data.map((d) => {
        d.startDate = is(String, d.startDate) ? new Date(d.startDate) : (d.startDate ? d.startDate : '');
        d.expirationDate = is(String, d.expirationDate) ? new Date(d.expirationDate) : (d.expirationDate ? d.expirationDate : '');
        return d;
    });

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

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

    const handleReopen = (amendmentId) => {
        setLocalAsyncRequest(true);
        AdminService.doAmendmentReopen(
            { amendment_id: amendmentId },
            (resp) => {
                if (resp && resp.status === 'ok') {
                    if (toast.current) {
                        toast.current.show({ severity: 'success', summary: '', detail: __('Soccorso riaperto con successo', 'gepafin') });
                    }
                }
                setLocalAsyncRequest(false);
            },
            (resp) => {
                if (toast.current) {
                    toast.current.show({ severity: 'error', summary: '', detail: resp ? resp.detail : __('Errore', 'gepafin') });
                }
                setLocalAsyncRequest(false);
            }
        );
    };

    const actionsBodyTemplate = (rowData) => (
        <div className="appPageSection__tableActions lessGap">
            <Button
                severity="warning"
                label={__('Re open', 'gepafin')}
                size="small"
                disabled={localAsyncRequest}
                onClick={() => handleReopen(rowData.id)}/>
        </div>
    );

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

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

    const statusFilterTemplate = (options) => (
        <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['status'] = { value: e.value, matchMode: 'equals' };
                } else {
                    delete filters['status'];
                }
                setLazyState({ ...lazyState, filters, first: 0 });
            }}
            itemTemplate={statusItemTemplate}
            placeholder={translationStrings.selectOneLabel}
            className="p-column-filter"/>
    );

    const dateFilterTemplate = (options) => (
        <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 dateStartBodyTemplate = (rowData) => getFormattedDateString(rowData.startDate);
    const dateExpirationBodyTemplate = (rowData) => rowData.expirationDate ? getFormattedDateString(rowData.expirationDate) : '';

    const clearFilter = () => {
        setLazyState({
            first: 0,
            rows: 5,
            page: 0,
            sortField: null,
            sortOrder: null,
            filters: {
                applicationId: { value: null, matchMode: 'equals' },
                callName: { value: null, matchMode: 'contains' },
                companyName: { value: null, matchMode: 'contains' },
                startDate: { value: null, matchMode: 'dateIs' },
                expirationDate: { value: null, matchMode: 'dateIs' },
                status: { value: null, matchMode: 'equals' }
            }
        });
    };

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

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

    return (
        <div className="appPageSection">
            <h2>{__('Riapertura soccorso istruttorio', '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="applicationId" header={__('ID domanda', 'gepafin')}
                            sortable
                            filterField="applicationId" filter
                            filterMatchModeOptions={translationStrings.numberFilterOptions}
                            filterPlaceholder={__('Cerca', 'gepafin')}
                            style={{ minWidth: '6rem' }}/>
                    <Column field="callName" header={__('Bando', 'gepafin')}
                            filterField="callName" 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 richiesta', 'gepafin')}
                            filterElement={dateFilterTemplate} filter
                            filterField="startDate" dataType="date"
                            filterMatchModeOptions={translationStrings.dateFilterOptions}
                            style={{ minWidth: '8rem' }}
                            body={dateStartBodyTemplate}/>
                    <Column header={__('Scadenza', 'gepafin')}
                            filterElement={dateFilterTemplate} filter
                            filterField="expirationDate" dataType="date"
                            filterMatchModeOptions={translationStrings.dateFilterOptions}
                            style={{ minWidth: '8rem' }}
                            body={dateExpirationBodyTemplate}/>
                    <Column field="status" header={__('Stato', 'gepafin')}
                            filterElement={statusFilterTemplate} filter
                            filterMatchModeOptions={translationStrings.statusFilterOptions}
                            style={{ minWidth: '8rem' }}
                            body={statusBodyTemplate}/>
                    <Column header={__('Azioni', 'gepafin')}
                            body={actionsBodyTemplate}/>
                </DataTable>
            </div>
        </div>
    );
};

export default ManageAmendmentReopenSection;
