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';
import getBandoLabel from '../../../../helpers/getBandoLabel';
import getBandoSeverity from '../../../../helpers/getBandoSeverity';

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

const allStatuses = [
    'SUBMIT', 'EVALUATION', 'SOCCORSO', 'APPOINTMENT', 'NDG', 'ADMISSIBLE',
    'AWAITING_TECHNICAL_EVALUATION', 'APPROVED', 'REJECTED'
];

const availableStatuses = [
    'EVALUATION', 'SOCCORSO', 'APPOINTMENT', 'NDG', 'ADMISSIBLE',
    'AWAITING_TECHNICAL_EVALUATION', 'APPROVED', 'REJECTED'
];

const ManageApplStatusSection = () => {
    const [localAsyncRequest, setLocalAsyncRequest] = useState(false);
    const [items, setItems] = useState(null);
    const [totalRecordsNum, setTotalRecordsNum] = useState(0);
    const [isStatusDialogVisible, setIsStatusDialogVisible] = useState(false);
    const [selectedAppId, setSelectedAppId] = useState(null);
    const [selectedStatus, setSelectedStatus] = useState(null);
    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' },
            status: { value: null, matchMode: 'equals' }
        }
    });
    const toast = useRef(null);

    const getPaginationQuery = useCallback(() => getQueryParamsForPaginatedEndpoint(lazyState, allStatuses, '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 openStatusDialog = (appId) => {
        setSelectedAppId(appId);
        setSelectedStatus(null);
        setIsStatusDialogVisible(true);
    };

    const hideStatusDialog = () => {
        setIsStatusDialogVisible(false);
        setSelectedAppId(null);
        setSelectedStatus(null);
    };

    const handleChangeStatus = useCallback(() => {
        setLocalAsyncRequest(true);
        const body = { application_id: selectedAppId, status: selectedStatus };

        AdminService.setApplStatus(body, callback, errCallback);
    }, [selectedStatus, selectedAppId]);

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

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

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

    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={allStatuses}
                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 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' },
                status: { value: null, matchMode: 'equals' }
            }
        });
    };

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

    const statusDialogFooter = (
        <div>
            <Button label={__('Annulla', 'gepafin')} icon="pi pi-times" outlined onClick={hideStatusDialog}/>
            <Button label={__('Salva', 'gepafin')} icon="pi pi-check" onClick={handleChangeStatus}
                    disabled={!selectedStatus}/>
        </div>
    );

    const header = renderHeader();

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

    return (
        <div className="appPageSection">
            <h2>{__('Gestione stato domande', '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="status" header={__('Stato', 'gepafin')}
                            filterElement={statusFilterTemplate} filter
                            filterMatchModeOptions={translationStrings.statusFilterOptions}
                            style={{ minWidth: '8rem' }}
                            body={statusBodyTemplate}/>
                    <Column header={__('Azioni', 'gepafin')}
                            body={actionsBodyTemplate}/>
                </DataTable>
            </div>

            <Dialog
                visible={isStatusDialogVisible}
                modal
                header={__('Cambia stato domanda', 'gepafin')}
                footer={statusDialogFooter}
                style={{ maxWidth: '500px', width: '100%' }}
                onHide={hideStatusDialog}>
                <div className="appForm__field">
                    <p>{__('Seleziona il nuovo stato', 'gepafin')}</p>
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.5rem', marginTop: '0.5rem' }}>
                        {availableStatuses.map((status) => (
                            <Tag
                                key={status}
                                value={getBandoLabel(status)}
                                severity={getBandoSeverity(status)}
                                onClick={() => setSelectedStatus(status)}
                                style={{
                                    cursor: 'pointer',
                                    outline: selectedStatus === status ? '2px solid var(--primary-color)' : 'none',
                                    outlineOffset: '2px'
                                }}/>
                        ))}
                    </div>
                </div>
            </Dialog>
        </div>
    );
};

export default ManageApplStatusSection;
