'use client';
export const dynamic = 'force-dynamic';


import React, { useState, useEffect, useRef } from 'react';
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { Button } from 'primereact/button';
import { InputText } from 'primereact/inputtext';
import { Card } from 'primereact/card';
import { Toast } from 'primereact/toast';
import { Toolbar } from 'primereact/toolbar';
import { Tag } from 'primereact/tag';
import { Badge } from 'primereact/badge';
import notificationService, { Notification } from '../../../../services/notificationService';
import { formatDistanceToNow } from 'date-fns';
import { fr } from 'date-fns/locale';

const NotificationsNonLuesPage = () => {
    const [notifications, setNotifications] = useState<Notification[]>([]);
    const [loading, setLoading] = useState(true);
    const [globalFilter, setGlobalFilter] = useState('');
    const toast = useRef<Toast>(null);
    const dt = useRef<DataTable<Notification[]>>(null);

    useEffect(() => {
        loadNotifications();
    }, []);

    const loadNotifications = async () => {
        try {
            setLoading(true);
            const data = await notificationService.getUnreadNotifications();
            setNotifications(data);
        } catch (error) {
            console.error('Erreur lors du chargement des notifications:', error);
            toast.current?.show({
                severity: 'error',
                summary: 'Erreur',
                detail: 'Impossible de charger les notifications non lues',
                life: 3000
            });
        } finally {
            setLoading(false);
        }
    };

    const markAsRead = async (notification: Notification) => {
        try {
            await notificationService.markAsRead(notification.id);
            setNotifications(notifications.filter(n => n.id !== notification.id));
            toast.current?.show({
                severity: 'success',
                summary: 'Succès',
                detail: 'Notification marquée comme lue',
                life: 2000
            });
        } catch (error) {
            console.error('Erreur:', error);
        }
    };

    const markAllAsRead = async () => {
        try {
            await notificationService.markAllAsRead();
            setNotifications([]);
            toast.current?.show({
                severity: 'success',
                summary: 'Succès',
                detail: 'Toutes les notifications ont été marquées comme lues',
                life: 3000
            });
        } catch (error) {
            console.error('Erreur:', error);
        }
    };

    const typeBodyTemplate = (rowData: Notification) => {
        const getSeverity = (type: string) => {
            switch (type) {
                case 'info': return 'info';
                case 'warning': return 'warning';
                case 'success': return 'success';
                case 'error': return 'danger';
                default: return 'info';
            }
        };

        const getIcon = (type: string) => {
            switch (type) {
                case 'info': return 'pi-info-circle';
                case 'warning': return 'pi-exclamation-triangle';
                case 'success': return 'pi-check-circle';
                case 'error': return 'pi-times-circle';
                default: return 'pi-info-circle';
            }
        };

        return (
            <Tag 
                value={rowData.type.toUpperCase()} 
                severity={getSeverity(rowData.type)}
                icon={`pi ${getIcon(rowData.type)}`}
            />
        );
    };

    const dateBodyTemplate = (rowData: Notification) => {
        return formatDistanceToNow(new Date(rowData.date), { 
            addSuffix: true, 
            locale: fr 
        });
    };

    const actionBodyTemplate = (rowData: Notification) => {
        return (
            <Button
                icon="pi pi-check"
                className="p-button-rounded p-button-text p-button-success"
                tooltip="Marquer comme lue"
                onClick={() => markAsRead(rowData)}
            />
        );
    };

    const leftToolbarTemplate = () => {
        return (
            <div className="flex align-items-center gap-2">
                <h5 className="m-0">Notifications non lues</h5>
                {notifications.length > 0 && (
                    <Badge value={notifications.length} severity="danger" />
                )}
            </div>
        );
    };

    const rightToolbarTemplate = () => {
        return (
            <div className="flex gap-2">
                <Button
                    label="Tout marquer comme lu"
                    icon="pi pi-check-square"
                    className="p-button-text"
                    onClick={markAllAsRead}
                    disabled={notifications.length === 0}
                />
                <Button
                    label="Actualiser"
                    icon="pi pi-refresh"
                    className="p-button-text"
                    onClick={loadNotifications}
                />
            </div>
        );
    };

    const header = (
        <div className="flex flex-column md:flex-row md:justify-content-between md:align-items-center">
            <h5 className="m-0">Notifications non lues</h5>
            <span className="block mt-2 md:mt-0 p-input-icon-left">
                <i className="pi pi-search" />
                <InputText
                    type="search"
                    placeholder="Rechercher..."
                    onInput={(e) => setGlobalFilter(e.currentTarget.value)}
                />
            </span>
        </div>
    );

    return (
        <div className="grid">
            <div className="col-12">
                <Card>
                    <Toast ref={toast} />
                    <Toolbar className="mb-4" left={leftToolbarTemplate} right={rightToolbarTemplate} />

                    {notifications.length === 0 && !loading ? (
                        <div className="text-center p-5">
                            <i className="pi pi-check-circle text-6xl text-green-500 mb-3"></i>
                            <h3>Aucune notification non lue</h3>
                            <p className="text-color-secondary">Vous êtes à jour !</p>
                        </div>
                    ) : (
                        <DataTable
                            ref={dt}
                            value={notifications}
                            dataKey="id"
                            paginator
                            rows={10}
                            rowsPerPageOptions={[5, 10, 25]}
                            className="datatable-responsive"
                            paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
                            currentPageReportTemplate="Affichage de {first} à {last} sur {totalRecords} notifications"
                            globalFilter={globalFilter}
                            emptyMessage="Aucune notification non lue."
                            header={header}
                            responsiveLayout="scroll"
                            loading={loading}
                            rowClassName={() => 'bg-blue-50'}
                        >
                            <Column field="type" header="Type" body={typeBodyTemplate} sortable style={{ minWidth: '8rem' }} />
                            <Column field="titre" header="Titre" sortable style={{ minWidth: '15rem' }} />
                            <Column field="message" header="Message" sortable style={{ minWidth: '20rem' }} />
                            <Column field="date" header="Date" body={dateBodyTemplate} sortable style={{ minWidth: '10rem' }} />
                            <Column header="Actions" body={actionBodyTemplate} style={{ minWidth: '8rem' }} />
                        </DataTable>
                    )}
                </Card>
            </div>
        </div>
    );
};

export default NotificationsNonLuesPage;

