import React, { useEffect, useState, useRef } from 'react';
import { __ } from '@wordpress/i18n';
import { intersection } from 'ramda';
import { useNavigate } from 'react-router-dom';

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

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

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

const buildDiffRows = (oldData, newData) => {
    const keys = Array.from(new Set([
        ...Object.keys(oldData || {}),
        ...Object.keys(newData || {})
    ]));
    return keys.map((key) => ({
        key,
        old: oldData ? String(oldData[key] ?? '') : '',
        new: newData ? String(newData[key] ?? '') : ''
    }));
};

const AdminLog = () => {
    const permissions = useStoreValue('getPermissions');
    const navigate = useNavigate();
    const toast = useRef(null);
    const hasPermission = intersection(permissions, ['ROOT_MANAGE_VIEW_LOG']).length > 0;

    const [callId, setCallId] = useState('');
    const [userId, setUserId] = useState('');
    const [dateFrom, setDateFrom] = useState(null);
    const [dateTo, setDateTo] = useState(null);
    const [items, setItems] = useState(null);
    const [totalRecordsNum, setTotalRecordsNum] = useState(0);
    const [loading, setLoading] = useState(false);
    const [lazyState, setLazyState] = useState({ first: 0, rows: 10, page: 0 });

    const [detailRow, setDetailRow] = useState(null);

    useEffect(() => {
        if (!hasPermission) navigate('/admin');
    }, [hasPermission]);

    const formatDate = (date) => {
        if (!date) return undefined;
        const d = new Date(date);
        const year = d.getFullYear();
        const month = String(d.getMonth() + 1).padStart(2, '0');
        const day = String(d.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    };

    const validate = () => {
        if ((dateFrom && !dateTo) || (!dateFrom && dateTo)) {
            toast.current.show({
                severity: 'warn',
                summary: __('Attenzione', 'gepafin'),
                detail: __('Inserire sia la data di inizio che la data di fine.', 'gepafin')
            });
            return false;
        }
        if (dateFrom && dateTo && dateFrom > dateTo) {
            toast.current.show({
                severity: 'warn',
                summary: __('Attenzione', 'gepafin'),
                detail: __('La data di inizio non può essere superiore alla data di fine.', 'gepafin')
            });
            return false;
        }
        return true;
    };

    const fetchData = (page = 0, rows = lazyState.rows) => {
        if (!validate()) return;
        setLoading(true);

        const queryParams = [
            ['page', page + 1],
            ['limit', rows]
        ];
        if (callId) queryParams.push(['call_id', callId]);
        if (userId) queryParams.push(['user_id', userId]);
        if (dateFrom) queryParams.push(['date_from', formatDate(dateFrom)]);
        if (dateTo) queryParams.push(['date_to', formatDate(dateTo)]);

        AdminService.getAdminLog(
            (resp) => {
                if (resp && resp.status === 'ok') {
                    setItems(resp.records || []);
                    setTotalRecordsNum(resp.totalRecords || 0);
                }
                setLoading(false);
            },
            () => { setLoading(false); },
            queryParams
        );
    };

    const onPage = (event) => {
        setLazyState(event);
        fetchData(event.page, event.rows);
    };

    const azioniTemplate = (row) => (
        <Button
            size="small"
            label={__('Mostra dettagli', 'gepafin')}
            icon="pi pi-eye"
            onClick={() => setDetailRow(row)}
        />
    );

    const userTemplate = (row) => {
        return `${row.utente.email}`;
    }

    return <div className="appPage">
        <Toast ref={toast}/>
        <div className="appPage__pageHeader">
            <h1>{__('Log Operazioni', 'gepafin')}</h1>
        </div>
        <div className="appPage__spacer"></div>
        <div className="appPageSection__actions">
            <Button type="button" outlined label={__('Indietro', 'gepafin')} icon="pi pi-arrow-left" onClick={() => navigate('/admin')}/>
        </div>
        <div className="appPage__spacer"></div>

        <div className="appPageSection">
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '1rem', marginBottom: '1rem' }}>
                <div className="formLayout__col">
                    <label htmlFor="callId">{__('ID Bando', 'gepafin')}</label>
                    <InputText
                        id="callId"
                        value={callId}
                        onChange={(e) => setCallId(e.target.value)}
                        style={{ width: '100%' }}
                    />
                </div>
                <div className="formLayout__col">
                    <label htmlFor="userId">{__('ID Utente', 'gepafin')}</label>
                    <InputText
                        id="userId"
                        value={userId}
                        onChange={(e) => setUserId(e.target.value)}
                        style={{ width: '100%' }}
                    />
                </div>
                <div className="formLayout__col">
                    <label htmlFor="dateFrom">{__('Data da', 'gepafin')}</label>
                    <Calendar
                        id="dateFrom"
                        value={dateFrom}
                        onChange={(e) => setDateFrom(e.value)}
                        dateFormat="dd/mm/yy"
                        showIcon
                        style={{ width: '100%' }}
                    />
                </div>
                <div className="formLayout__col">
                    <label htmlFor="dateTo">{__('Data a', 'gepafin')}</label>
                    <Calendar
                        id="dateTo"
                        value={dateTo}
                        onChange={(e) => setDateTo(e.value)}
                        dateFormat="dd/mm/yy"
                        showIcon
                        style={{ width: '100%' }}
                    />
                </div>
            </div>
            <Button
                label={__('Cerca', 'gepafin')}
                icon="pi pi-search"
                size="small"
                onClick={() => {
                    setLazyState((s) => ({ ...s, first: 0, page: 0 }));
                    fetchData(0);
                }}
                loading={loading}
            />
        </div>

        <div className="appPage__spacer"></div>

        <div className="appPageSection__table">
            <DataTable
                value={items}
                lazy
                paginator
                first={lazyState.first}
                rows={lazyState.rows}
                totalRecords={totalRecordsNum}
                onPage={onPage}
                loading={loading}
                emptyMessage={__('Nessun risultato trovato.', 'gepafin')}
            >
                <Column field="user_action_id" header={__('ID', 'gepafin')}/>
                <Column field="call_id" header={__('ID Bando', 'gepafin')}/>
                <Column field="periodo" header={__('Periodo', 'gepafin')}/>
                <Column header={__('Utente', 'gepafin')} body={userTemplate}/>
                <Column field="action_context" header={__('Azione', 'gepafin')}/>
                <Column header={__('Azioni', 'gepafin')} body={azioniTemplate}/>
            </DataTable>
        </div>

        <Dialog
            header={__('Dettagli operazione', 'gepafin')}
            visible={!!detailRow}
            style={{ width: '80vw' }}
            onHide={() => setDetailRow(null)}
        >
            {detailRow && (detailRow.version_history || []).map((vh, idx) => (
                <div key={vh.version_history_id ?? idx} style={{ marginBottom: '1.5rem' }}>
                    <h3 style={{ marginBottom: '0.5rem' }}>
                        {vh.table_name} — {vh.version_history_action_type}
                    </h3>
                    <DataTable
                        value={buildDiffRows(vh.old_data, vh.new_data)}
                        size="small"
                        scrollable
                        scrollHeight="300px"
                        emptyMessage={__('Nessun dato.', 'gepafin')}
                    >
                        <Column field="key" header={__('Campo', 'gepafin')} style={{ width: '30%' }}/>
                        <Column field="old" header={__('Vecchio valore', 'gepafin')} style={{ width: '35%' }}/>
                        <Column field="new" header={__('Nuovo valore', 'gepafin')} style={{ width: '35%' }}/>
                    </DataTable>
                </div>
            ))}
        </Dialog>
    </div>
}

export default AdminLog;
