import { useState, useRef, useEffect } from 'react'; import { useSetupData, SetupData } from "@/context/SetupDataContext"; import EditIcon from '@mui/icons-material/Edit'; import AddIcon from '@mui/icons-material/Add'; import RefreshIcon from '@mui/icons-material/Refresh'; import CancelIcon from '@mui/icons-material/Cancel'; import { List, Card, CardContent, Typography, Box, useTheme, useMediaQuery, CircularProgress, IconButton } from '@mui/material'; import { DataGrid, GridColDef, GridRenderCellParams, GridRowModel, GridToolbarContainer, GridToolbarQuickFilter, GridToolbarExport, GridToolbarDensitySelector, GridToolbarColumnsButton } from '@mui/x-data-grid'; import Mailing from '@/types/mailing'; //import Template from '@/types/template'; import MailingEdit from "@/components/modals/MailingEdit"; import ConfirmationDialog from "@/components/modals/ConfirmationDialog"; import { useCustomFetch } from "@/utils/customFetch"; function NewMailings() { const customFetch = useCustomFetch(); const theme = useTheme(); const setupData: SetupData = useSetupData(); const isMobile = useMediaQuery(theme.breakpoints.down("sm")); const gridContainerRef = useRef(null); const [mailingsLoading, setMailingsLoading] = useState(false); const [mailings, setMailings] = useState([]); const [selectedRow, setSelectedRow] = useState(null); const [open, setOpen] = useState(false); const [confirmDialogOpen, setConfirmDialogOpen] = useState(false); const [mailingToCancel, setMailingToCancel] = useState(null); const columns: GridColDef[] = [ { field: "actions", headerName: "", sortable: false, width: 100, renderCell: (params: GridRenderCellParams) => ( <> { e.stopPropagation(); handleEdit(params.row); }}> { e.stopPropagation(); handleCancelClick(params.row); }}> ), }, { field: "id", headerName: "ID", width: 80 }, { field: "name", headerName: "Name", flex: 1, minWidth: 160 }, { field: "description", headerName: "Description", flex: 1, minWidth: 200 }, { field: "templateId", headerName: "Subject", flex: 1, minWidth: 160, valueGetter: (_: number, row: Mailing) => setupData.templates.find(t => t.id === row.templateId)?.subject || 'Unknown', }, ]; const reloadMailings = async () => { setMailingsLoading(true); const mailingsResponse = await customFetch("/api/mailings/status/ed"); const mailingsData = await mailingsResponse.json(); if (mailingsData) { setMailings(mailingsData); setMailingsLoading(false); } else { console.error("Failed to fetch mailings"); setMailingsLoading(false); } } const handleNew = () => { setSelectedRow(null); setOpen(true); }; const handleEdit = (row: GridRowModel) => { setSelectedRow(row); setOpen(true); }; const handleUpdateRow = (updatedRow: Mailing) => { if (updatedRow.statusCode.toUpperCase() !== "ED") removeMailing(updatedRow); else updateMailings(updatedRow); }; const handleCancelClick = (row: Mailing) => { setMailingToCancel(row); setConfirmDialogOpen(true); }; const handleCancelConfirm = async () => { if (!mailingToCancel) return; try { const response = await customFetch(`/api/mailings/${mailingToCancel.id}/cancel`, { method: 'POST' }); if (response.ok) { setMailings((prev) => prev.filter(m => m.id !== mailingToCancel.id)); } else { console.error("Failed to cancel mailing"); } } catch (error) { console.error("Error cancelling mailing:", error); } finally { setConfirmDialogOpen(false); setMailingToCancel(null); } }; const handleCancelDialogClose = () => { setConfirmDialogOpen(false); setMailingToCancel(null); }; useEffect(() => { reloadMailings(); }, []); const removeMailing = (mailing: Mailing) => { setMailings((prevMailings) => { return prevMailings.filter(el => el.id !== mailing.id); }); } const updateMailings = (updatedMailing: Mailing) => { setMailings((prev) => { const exists = prev.some((e) => e.id === updatedMailing.id); return exists ? prev.map((server) => (server.id === updatedMailing.id ? updatedMailing : server)) : [...prev, updatedMailing]; }); }; return ( {isMobile ? ( {mailings.map((row) => ( {row.name} ID: {row.id} Description: {row.description} Subject: {setupData.templates.find(t => t.id === row.templateId)?.subject || 'Unknown'} { e.stopPropagation(); handleEdit(row); }}> handleCancelClick(row)}> ))} ) : ( ( reloadMailings()} sx={{ marginLeft: 1 }}> {mailingsLoading ? : } ), }} slotProps={{ toolbar: { showQuickFilter: true, }, }} initialState={{ pagination: { paginationModel: { pageSize: 20, }, }, sorting: { sortModel: [{ field: 'id', sort: 'asc' }], }, }} pageSizeOptions={[10, 20, 50, 100]} /> )} {open && ( { if (reason !== 'backdropClick') setOpen(false) }} onSave={handleUpdateRow} /> )} {confirmDialogOpen && ( )} ); } export default NewMailings;