import { useEffect } from 'react';
import { Button, Spinner } from '@wordpress/components';
import NotificationHeader from './NotificationHeader';
import { useNotificationContext } from '../context/NotificationContext';

export default function NotificationList() {

    const { notifications, loading, deleteNotification, fetchNotifications, openModal } = useNotificationContext();

    const handleDelete = async (notificationID) => {
        if (window.confirm('Are you sure you want to delete this notification?')) {
            await deleteNotification(notificationID);
            fetchNotifications();
        }
    }

    const NotificationBody = () => {
        return <>
            {notifications.length === 0 && <p>No notifications found.</p>}

            {notifications.length > 0 && <div className="notification-table-container">
                <table className="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <th style={{ width: '5%' }}>ID</th>
                            <th style={{ width: '40%' }}>Name</th>
                            <th style={{ width: '20%' }}>Type</th>
                            <th style={{ width: '15%' }}>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        {notifications.map((notification) => (
                            <tr key={notification.id}>
                                <td>{notification.id}</td>
                                <td>{notification.name}</td>
                                <td>{notification.notification_type}</td>
                                <td>
                                    <Button
                                        onClick={() => openModal(notification.id)}
                                    >
                                        Edit
                                    </Button>
                                    <Button
                                        isDestructive
                                        onClick={() => handleDelete(notification.id)}
                                    >
                                        Delete
                                    </Button>
                                </td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            </div>}
        </>
    }

    return (
        <>
            <NotificationHeader />
            {!loading ? <NotificationBody /> : <Spinner />}
        </>
    );
}