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

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

// tools
import getBandoSeverity from '../../../../../../helpers/getBandoSeverity';
import getBandoLabel from '../../../../../../helpers/getBandoLabel';
import getDateFromISOstring from '../../../../../../helpers/getDateFromISOstring';

// api
import CompanyDocumentsService from '../../../../../../service/company-documents-service';

// components
import { FilterMatchMode, FilterOperator } from 'primereact/api';
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { Dropdown } from 'primereact/dropdown';
import { Button } from 'primereact/button';
import { Calendar } from 'primereact/calendar';
import { Tag } from 'primereact/tag';
import { Toast } from 'primereact/toast';
import ProperBandoLabel from '../../../../../../components/ProperBandoLabel';

const CompanyDocsTable = ({ type, reload = 0, companyId: companyIdProp, applicationId, onImportSuccess = () => {} }) => {
    const storedCompanyId = useStoreValue('chosenCompanyId');
    const effectiveCompanyId = companyIdProp || storedCompanyId;
    const companies = useStoreValue('companies');
    const [docs, setDocs] = useState([]);
    const [filters, setFilters] = useState(null);
    const [loading, setLoading] = useState(false);
    const [statuses, setStatuses] = useState([]);
    const toast = useRef(null);

    useEffect(() => {
        const shouldFetch = companyIdProp
            ? !!effectiveCompanyId
            : !!head(companies.filter(o => o.id === effectiveCompanyId));

        if (!loading && shouldFetch && reload !== 0) {
            setLoading(true);
            CompanyDocumentsService.getCompanyDocuments(effectiveCompanyId, getCallback, errGetCallbacks, [
                ['documentType', type]
            ]);
        }
    }, [effectiveCompanyId, reload, companies]);

    useEffect(() => {
        const shouldFetch = companyIdProp
            ? !!effectiveCompanyId
            : !!head(companies.filter(o => o.id === effectiveCompanyId));

        if (shouldFetch) {
            setLoading(true);
            CompanyDocumentsService.getCompanyDocuments(effectiveCompanyId, getCallback, errGetCallbacks, [
                ['documentType', type]
            ]);
        }
    }, []);

    const getCallback = (resp) => {
        if (resp.status === 'SUCCESS') {
            setDocs(getFormattedData(resp.data));
            setStatuses(uniq(resp.data.map(o => o.status)))
            initFilters();
        }
        setLoading(false);
    }

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

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

    const clearFilter = () => {
        initFilters();
    };

    const initFilters = () => {
        setFilters({
            name: {
                operator: FilterOperator.AND,
                constraints: [{ value: null, matchMode: FilterMatchMode.STARTS_WITH }]
            },
            createdDate: {
                operator: FilterOperator.AND,
                constraints: [{ value: null, matchMode: FilterMatchMode.DATE_IS }]
            },
            expirationDate: {
                operator: FilterOperator.AND,
                constraints: [{ value: null, matchMode: FilterMatchMode.DATE_IS }]
            }
        });
    };

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

    const dateCreatedBodyTemplate = (rowData) => {
        return getDateFromISOstring(rowData.createdDate);
    };
    const dateExpirationBodyTemplate = (rowData) => {
        return getDateFromISOstring(rowData.expirationDate);
    };

    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 catBodyTemplate = (rowData) => {
        return rowData.category.categoryName;
    };

    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={__('Scegli uno', 'gepafin')}
                         className="p-column-filter"/>;
    };

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

    const handleImportDoc = (id) => {
        setLoading(true);
        CompanyDocumentsService.attachCompanyDocumentToAppl(id, importCallback, errImportCallback, [
            ['applicationId', applicationId],
            ['documentType', 'DOCUMENT']
        ])
    };

    const importCallback = (resp) => {
        setLoading(false);
        if (toast.current) {
            toast.current.show({
                severity: resp.status === 'SUCCESS' ? 'success' : 'error',
                summary: '',
                detail: resp.message
            });
        }
        if (resp.status === 'SUCCESS') {
            onImportSuccess();
        }
    };

    const errImportCallback = (resp) => {
        setLoading(false);
        if (toast.current && resp.message) {
            toast.current.show({ severity: 'error', summary: '', detail: resp.message });
        }
    };

    const actionsBodyTemplate = (rowData) => {
        return <div className="appPageSection__iconActions">
            <Button icon="pi pi-eye" rounded
                    onClick={() => {
                        window.open(rowData.filePath, '_blank').focus()
                    }}
                    outlined severity="info"
                    aria-label={__('Mostra', 'gepafin')}/>
            <Button icon="pi pi-download" rounded
                    onClick={() => handleImportDoc(rowData.id)}
                    outlined severity="success"
                    aria-label={__('Importa', 'gepafin')}/>
        </div>
    }

    const header = renderHeader();

    return (
        <>
            <Toast ref={toast}/>
            <div className="appPageSection__table">
                <DataTable value={docs} paginator showGridlines rows={5} loading={loading} dataKey="id"
                           filters={filters} stripedRows removableSort
                           header={header}
                           onFilter={(e) => setFilters(e.filters)}>
                    <Column field="name"
                            header={__('Nome documento', 'gepafin')}
                            filter filterField="name"
                            filterPlaceholder={__('Cerca per nome', 'gepafin')}
                            style={{ minWidth: '12rem' }}/>
                    <Column body={catBodyTemplate} header={__('Categoria', 'gepafin')}
                            style={{ minWidth: '8rem' }}/>
                    <Column header={__('Data caricamento', 'gepafin')}
                            filterField="createdDate" dataType="date"
                            style={{ minWidth: '7rem' }}
                            body={dateCreatedBodyTemplate} filter filterElement={dateFilterTemplate}/>
                    <Column header={__('Data scadenza', 'gepafin')}
                            filterField="expirationDate" dataType="date"
                            style={{ minWidth: '7rem' }}
                            body={dateExpirationBodyTemplate} filter filterElement={dateFilterTemplate}/>
                    <Column field="status" header={__('Stato', 'gepafin')}
                            filterMenuStyle={{ width: '14rem' }}
                            style={{ width: '120px' }} body={statusBodyTemplate}
                            filterElement={statusFilterTemplate}/>
                    <Column header={__('Azioni', 'gepafin')}
                            body={actionsBodyTemplate}/>
                </DataTable>
            </div>
        </>
    )
}

export default CompanyDocsTable;
