import StyledTable from "@/Components/Admin/ui/StyledTable";
import { useEffect, useState, useRef } from "react";
import { router, usePage } from '@inertiajs/react';
import { toast, Toaster } from "react-hot-toast";
import DeleteConfirmationModal from "@/Components/Admin/ui/DeleteConfirmationModal";

export default function Notification({ notifications, pagination }) {
    const { flash } = usePage().props;
    const processedMessages = useRef(new Set());
    
    const [notificationData, setNotificationData] = useState([]);
    const [deleteModal, setDeleteModal] = useState({ show: false, notification: null });

    useEffect(() => {
        if (flash?.success) {
            const message = typeof flash.success === 'object' ? flash.success.message : flash.success;
            if (message && !processedMessages.current.has(`success-${message}`)) {
                toast.success(message);
                processedMessages.current.add(`success-${message}`);
            }
        }
        if (flash?.error) {
            const message = typeof flash.error === 'object' ? flash.error.message : flash.error;
            if (message && !processedMessages.current.has(`error-${message}`)) {
                toast.error(message);
                processedMessages.current.add(`error-${message}`);
            }
        }
    }, [flash]);

    useEffect(() => {
        setNotificationData(notifications || []);
    }, [notifications]);

    const columns = [
        { key: 'sn', header: 'SN' },
        { key: 'user_name', header: 'User' },
        { key: 'type_text', header: 'Type' },
        { key: 'title', header: 'Title' },
        { key: 'body', header: 'Message' },
        { key: 'is_read', header: 'Status' },
        { key: 'created_at', header: 'Date' }
    ];

    const transformedData = notificationData.map(notification => ({
        ...notification,
        body: notification.body?.length > 50 ? `${notification.body.substring(0, 50)}...` : notification.body || 'N/A',
        is_read: notification.is_read ? 'read' : 'unread',
        created_at: new Date(notification.created_at).toLocaleDateString(),
    }));

    const handlePageChange = (page) => {
        router.get('/admin/notifications', { page }, { preserveState: true, preserveScroll: true });
    };

    const handleDelete = (row) => {
        setDeleteModal({ show: true, notification: row });
    };

    return (
        <>
            <Toaster />
            <div className="row">
                <StyledTable
                    data={transformedData}
                    columns={columns}
                    title="Notification Management"
                    onDelete={handleDelete}
                    noDataText="No notifications found in the system"
                    disablePagination={true}
                    serverPagination={pagination}
                    onPageChange={handlePageChange}
                    itemType="notifications"
                    showEdit={false}
                />
            </div>

            <DeleteConfirmationModal
                isOpen={deleteModal.show}
                onClose={() => setDeleteModal({ show: false, notification: null })}
                onConfirmDelete={() => {}}
                itemName={`Notification #${deleteModal.notification?.id}` || 'this notification'}
                itemType="notification"
                deleteEndpoint={`/admin/notifications/${deleteModal?.notification?.id}`}
            />
        </>
    );
}
