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

// components
import { FilterMatchMode, FilterOperator } from 'primereact/api';
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { InputText } from 'primereact/inputtext';
import { IconField } from 'primereact/iconfield';
import { InputIcon } from 'primereact/inputicon';
import { Button } from 'primereact/button';
import { Calendar } from 'primereact/calendar';

const LatestUsersActivityTable = () => {
    const [items, setItems] = useState(null);
    const [filters, setFilters] = useState(null);
    const [loading, setLoading] = useState(false);
    const [globalFilterValue, setGlobalFilterValue] = useState('');

    useEffect(() => {
        // TODO
        const bandi = [
            {
                date: '2024-08-02T00:00:00+14:32',
                email: 'mario.rossi@gepafin.it',
                action: 'Valutazione Domanda',
                details: 'Bando Innovazione 2024 - Domanda #123',
                id: 11
            },
            {
                date: '2024-08-01T00:00:00+08:23',
                email: 'laura.bianchi@gepafin.it',
                action: 'Creazione Bando',
                details: 'Nuovo bando "Formazione 2025" in bozza',
                id: 9
            }
        ]
        setItems(getFormattedBandiData(bandi));
        setLoading(false);
        initFilters();
    }, []);

    const getFormattedBandiData = (data) => {
        return [...(data || [])].map((d) => {
            d.date = new Date(d.date);

            return d;
        });
    };

    const formatDate = (value) => {
        return value.toLocaleDateString('it-IT', {
            day: '2-digit',
            month: '2-digit',
            year: 'numeric'
        });
    };

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

    const onGlobalFilterChange = (e) => {
        const value = e.target.value;
        let _filters = { ...filters };

        _filters['global'].value = value;

        setFilters(_filters);
        setGlobalFilterValue(value);
    };

    const initFilters = () => {
        setFilters({
            global: { value: null, matchMode: FilterMatchMode.CONTAINS },
            email: { operator: FilterOperator.AND, constraints: [{ value: null, matchMode: FilterMatchMode.STARTS_WITH }] },
            date: { operator: FilterOperator.AND, constraints: [{ value: null, matchMode: FilterMatchMode.DATE_IS }] },
        });
        setGlobalFilterValue('');
    };

    const renderHeader = () => {
        return (
            <div className="appTableHeader">
                <Button type="button" icon="pi pi-filter-slash" label={__('Pulisci', 'gepafin')} outlined onClick={clearFilter} />
                <IconField iconPosition="left">
                    <InputIcon className="pi pi-search" />
                    <InputText value={globalFilterValue} onChange={onGlobalFilterChange} placeholder={__('Cerca', 'gepafin')} />
                </IconField>
            </div>
        );
    };

    const dateBodyTemplate = (rowData) => {
        return formatDate(rowData.date);
    };

    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 header = renderHeader();

    return(
        <div className="appPageSection__table">
            <DataTable value={items} paginator showGridlines rows={5} loading={loading} dataKey="id"
                       filters={filters}
                       globalFilterFields={['name', 'status']}
                       header={header}
                       emptyMessage={translationStrings.emptyMessage}{__('Nessun dato disponibile', 'gepafin')}
                       onFilter={(e) => setFilters(e.filters)}>
                <Column header={__('Timestamp', 'gepafin')} filterField="date" dataType="date"
                        style={{ minWidth: '8rem' }}
                        body={dateBodyTemplate} filter filterElement={dateFilterTemplate}/>
                <Column field="email" header={__('Utente', 'gepafin')} filter filterPlaceholder="Search by email"
                        style={{ minWidth: '8rem' }}/>
                <Column field="action" header={__('Azione', 'gepafin')}/>
                <Column field="dettails" header={__('Dettagli', 'gepafin')}/>
            </DataTable>
        </div>
    )
}

export default LatestUsersActivityTable;