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


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

const NotificationsTableauBordPage = () => {
    const [notifications, setNotifications] = useState<Notification[]>([]);
    const [stats, setStats] = useState<NotificationStats | null>(null);
    const [loading, setLoading] = useState(true);
    const toast = useRef<Toast>(null);

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

    const loadData = async () => {
        try {
            setLoading(true);
            const [notifData, statsData] = await Promise.all([
                notificationService.getNotifications(),
                notificationService.getNotificationStats()
            ]);
            // Prendre les 5 dernières notifications
            const recentNotifications = notifData
                .sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
                .slice(0, 5);
            setNotifications(recentNotifications);
            setStats(statsData);
        } catch (error) {
            console.error('Erreur lors du chargement des données:', error);
            toast.current?.show({
                severity: 'error',
                summary: 'Erreur',
                detail: 'Impossible de charger le tableau de bord',
                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
            ));
            loadData(); // Recharger pour mettre à jour les stats
        } catch (error) {
            console.error('Erreur:', error);
        }
    };

    const chartData = stats ? {
        labels: ['Info', 'Avertissement', 'Succès', 'Erreur'],
        datasets: [
            {
                data: [
                    stats.parType.info || 0,
                    stats.parType.warning || 0,
                    stats.parType.success || 0,
                    stats.parType.error || 0
                ],
                backgroundColor: [
                    '#3B82F6',
                    '#F59E0B',
                    '#10B981',
                    '#EF4444'
                ]
            }
        ]
    } : null;

    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 !rowData.lu ? (
            <Button
                icon="pi pi-check"
                className="p-button-rounded p-button-text p-button-success"
                tooltip="Marquer comme lue"
                onClick={() => markAsRead(rowData)}
            />
        ) : null;
    };

    const pourcentageLues = stats && stats.total > 0 
        ? Math.round(((stats.total - stats.nonLues) / stats.total) * 100) 
        : 0;

    if (loading) {
        return (
            <div className="grid">
                <div className="col-12">
                    <Card>
                        <div className="text-center p-5">
                            <i className="pi pi-spin pi-spinner text-4xl"></i>
                            <p>Chargement du tableau de bord...</p>
                        </div>
                    </Card>
                </div>
            </div>
        );
    }

    return (
        <div className="grid">
            <div className="col-12">
                <div className="flex justify-content-between align-items-center mb-4">
                    <h2 className="m-0">Tableau de Bord des Notifications</h2>
                    <Button
                        label="Actualiser"
                        icon="pi pi-refresh"
                        className="p-button-text"
                        onClick={loadData}
                    />
                </div>
            </div>

            <Toast ref={toast} />

            {/* Cartes de statistiques */}
            <div className="col-12 md:col-6 lg:col-3">
                <Card>
                    <div className="flex justify-content-between align-items-center">
                        <div>
                            <span className="block text-500 font-medium mb-3">Total</span>
                            <div className="text-900 font-medium text-xl">{stats?.total || 0}</div>
                        </div>
                        <div className="flex align-items-center justify-content-center bg-blue-100 border-round" style={{ width: '2.5rem', height: '2.5rem' }}>
                            <i className="pi pi-bell text-blue-500 text-xl"></i>
                        </div>
                    </div>
                </Card>
            </div>

            <div className="col-12 md:col-6 lg:col-3">
                <Card>
                    <div className="flex justify-content-between align-items-center">
                        <div>
                            <span className="block text-500 font-medium mb-3">Non lues</span>
                            <div className="text-900 font-medium text-xl">{stats?.nonLues || 0}</div>
                        </div>
                        <div className="flex align-items-center justify-content-center bg-orange-100 border-round" style={{ width: '2.5rem', height: '2.5rem' }}>
                            <i className="pi pi-exclamation-circle text-orange-500 text-xl"></i>
                        </div>
                    </div>
                </Card>
            </div>

            <div className="col-12 md:col-6 lg:col-3">
                <Card>
                    <div className="flex justify-content-between align-items-center">
                        <div>
                            <span className="block text-500 font-medium mb-3">Lues</span>
                            <div className="text-900 font-medium text-xl">{stats ? stats.total - stats.nonLues : 0}</div>
                        </div>
                        <div className="flex align-items-center justify-content-center bg-green-100 border-round" style={{ width: '2.5rem', height: '2.5rem' }}>
                            <i className="pi pi-check-circle text-green-500 text-xl"></i>
                        </div>
                    </div>
                </Card>
            </div>

            <div className="col-12 md:col-6 lg:col-3">
                <Card>
                    <div className="flex justify-content-between align-items-center">
                        <div>
                            <span className="block text-500 font-medium mb-3">Taux de lecture</span>
                            <div className="text-900 font-medium text-xl">{pourcentageLues}%</div>
                        </div>
                        <div className="flex align-items-center justify-content-center bg-cyan-100 border-round" style={{ width: '2.5rem', height: '2.5rem' }}>
                            <i className="pi pi-chart-line text-cyan-500 text-xl"></i>
                        </div>
                    </div>
                </Card>
            </div>

            {/* Graphique et notifications récentes */}
            <div className="col-12 lg:col-6">
                <Card title="Répartition par type">
                    {chartData && <Chart type="doughnut" data={chartData} />}
                </Card>
            </div>

            <div className="col-12 lg:col-6">
                <Card title="Notifications récentes">
                    <DataTable
                        value={notifications}
                        dataKey="id"
                        responsiveLayout="scroll"
                        emptyMessage="Aucune notification"
                        rowClassName={(data) => !data.lu ? 'bg-blue-50' : ''}
                    >
                        <Column field="type" header="Type" body={typeBodyTemplate} style={{ width: '100px' }} />
                        <Column field="titre" header="Titre" style={{ minWidth: '200px' }} />
                        <Column field="date" header="Date" body={dateBodyTemplate} style={{ width: '150px' }} />
                        <Column header="Actions" body={actionBodyTemplate} style={{ width: '80px' }} />
                    </DataTable>
                    <div className="mt-3 text-center">
                        <Button
                            label="Voir toutes les notifications"
                            icon="pi pi-arrow-right"
                            className="p-button-text"
                            onClick={() => window.location.href = '/notifications'}
                        />
                    </div>
                </Card>
            </div>

            {/* Détails par type */}
            <div className="col-12">
                <Card title="Activité par type">
                    <div className="grid">
                        <div className="col-12 md:col-6 lg:col-3">
                            <div className="p-3 border-round bg-blue-50">
                                <div className="flex justify-content-between align-items-center mb-3">
                                    <span className="text-blue-700 font-medium">Info</span>
                                    <i className="pi pi-info-circle text-blue-500 text-2xl"></i>
                                </div>
                                <div className="text-blue-900 font-bold text-2xl mb-2">{stats?.parType.info || 0}</div>
                                <ProgressBar 
                                    value={stats && stats.total > 0 ? (stats.parType.info / stats.total) * 100 : 0} 
                                    showValue={false}
                                    color="#3B82F6"
                                />
                            </div>
                        </div>

                        <div className="col-12 md:col-6 lg:col-3">
                            <div className="p-3 border-round bg-orange-50">
                                <div className="flex justify-content-between align-items-center mb-3">
                                    <span className="text-orange-700 font-medium">Avertissement</span>
                                    <i className="pi pi-exclamation-triangle text-orange-500 text-2xl"></i>
                                </div>
                                <div className="text-orange-900 font-bold text-2xl mb-2">{stats?.parType.warning || 0}</div>
                                <ProgressBar 
                                    value={stats && stats.total > 0 ? (stats.parType.warning / stats.total) * 100 : 0} 
                                    showValue={false}
                                    color="#F59E0B"
                                />
                            </div>
                        </div>

                        <div className="col-12 md:col-6 lg:col-3">
                            <div className="p-3 border-round bg-green-50">
                                <div className="flex justify-content-between align-items-center mb-3">
                                    <span className="text-green-700 font-medium">Succès</span>
                                    <i className="pi pi-check-circle text-green-500 text-2xl"></i>
                                </div>
                                <div className="text-green-900 font-bold text-2xl mb-2">{stats?.parType.success || 0}</div>
                                <ProgressBar 
                                    value={stats && stats.total > 0 ? (stats.parType.success / stats.total) * 100 : 0} 
                                    showValue={false}
                                    color="#10B981"
                                />
                            </div>
                        </div>

                        <div className="col-12 md:col-6 lg:col-3">
                            <div className="p-3 border-round bg-red-50">
                                <div className="flex justify-content-between align-items-center mb-3">
                                    <span className="text-red-700 font-medium">Erreur</span>
                                    <i className="pi pi-times-circle text-red-500 text-2xl"></i>
                                </div>
                                <div className="text-red-900 font-bold text-2xl mb-2">{stats?.parType.error || 0}</div>
                                <ProgressBar 
                                    value={stats && stats.total > 0 ? (stats.parType.error / stats.total) * 100 : 0} 
                                    showValue={false}
                                    color="#EF4444"
                                />
                            </div>
                        </div>
                    </div>
                </Card>
            </div>
        </div>
    );
};

export default NotificationsTableauBordPage;

