'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 { Chip } from 'primereact/chip';
import { ConfirmDialog, confirmDialog } from 'primereact/confirmdialog';
import notificationService, { Notification } from '../../../services/notificationService';
import { formatDistanceToNow } from 'date-fns';
import { fr } from 'date-fns/locale';

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

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

    const loadNotifications = async () => {
        try {
            setLoading(true);
            const data = await notificationService.getNotifications();
            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',
                life: 3000
            });
        } finally {
            setLoading(false);
        }
    };

    const markAsRead = async (notification: Notification) => {
        try {
            await notificationService.markAsRead(notification.id);
            setNotifications(notifications.map(n => 
                n.id === notification.id ? { ...n, lu: true } : n
            ));
            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(notifications.map(n => ({ ...n, lu: true })));
            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 deleteNotification = async (notification: Notification) => {
        confirmDialog({
            message: 'Êtes-vous sûr de vouloir supprimer cette notification ?',
            header: 'Confirmation',
            icon: 'pi pi-exclamation-triangle',
            acceptLabel: 'Oui',
            rejectLabel: 'Non',
            accept: async () => {
                try {
                    await notificationService.deleteNotification(notification.id);
                    setNotifications(notifications.filter(n => n.id !== notification.id));
                    toast.current?.show({
                        severity: 'success',
                        summary: 'Succès',
                        detail: 'Notification supprimée',
                        life: 3000
                    });
                } catch (error) {
                    console.error('Erreur:', error);
                    toast.current?.show({
                        severity: 'error',
                        summary: 'Erreur',
                        detail: 'Impossible de supprimer la notification',
                        life: 3000
                    });
                }
            }
        });
    };

    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 statusBodyTemplate = (rowData: Notification) => {
        return rowData.lu ? (
            <Chip label="Lue" className="bg-gray-300" />
        ) : (
            <Chip label="Non lue" className="bg-blue-500 text-white" />
        );
    };

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

    const actionBodyTemplate = (rowData: Notification) => {
        return (
            <div className="flex gap-2">
                {!rowData.lu && (
                    <Button
                        icon="pi pi-check"
                        className="p-button-rounded p-button-text p-button-success"
                        tooltip="Marquer comme lue"
                        onClick={() => markAsRead(rowData)}
                    />
                )}
                <Button
                    icon="pi pi-trash"
                    className="p-button-rounded p-button-text p-button-danger"
                    tooltip="Supprimer"
                    onClick={() => deleteNotification(rowData)}
                />
            </div>
        );
    };

    const leftToolbarTemplate = () => {
        const unreadCount = notifications.filter(n => !n.lu).length;
        return (
            <div className="flex align-items-center gap-2">
                <h5 className="m-0">Notifications</h5>
                {unreadCount > 0 && (
                    <Badge value={unreadCount} 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.filter(n => !n.lu).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">Toutes les notifications</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} />
                    <ConfirmDialog />
                    <Toolbar className="mb-4" left={leftToolbarTemplate} right={rightToolbarTemplate} />

                    <DataTable
                        ref={dt}
                        value={notifications}
                        selection={selectedNotifications}
                        onSelectionChange={(e) => setSelectedNotifications(e.value)}
                        selectionMode="checkbox"
                        dataKey="id"
                        paginator
                        rows={10}
                        rowsPerPageOptions={[5, 10, 25, 50]}
                        className="datatable-responsive"
                        paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
                        currentPageReportTemplate="Affichage de {first} à {last} sur {totalRecords} notifications"
                        globalFilter={globalFilter}
                        emptyMessage="Aucune notification trouvée."
                        header={header}
                        responsiveLayout="scroll"
                        loading={loading}
                        rowClassName={(data) => !data.lu ? 'bg-blue-50' : ''}
                    >
                        <Column selectionMode="multiple" headerStyle={{ width: '3rem' }} />
                        <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 field="lu" header="Statut" body={statusBodyTemplate} sortable style={{ minWidth: '8rem' }} />
                        <Column header="Actions" body={actionBodyTemplate} style={{ minWidth: '10rem' }} />
                    </DataTable>
                </Card>
            </div>
        </div>
    );
};

export default NotificationsPage;

