import React, { useState, useEffect, useRef } from 'react'; import { Area } from '../../entities/Area'; import { Project } from '../../entities/Project'; import ConfirmDialog from '../Shared/ConfirmDialog'; import { useToast } from '../Shared/ToastContext'; import { XMarkIcon } from '@heroicons/react/24/outline'; interface ProjectModalProps { isOpen: boolean; onClose: () => void; onSave: (project: Project) => void; onDelete?: (projectId: number) => void; project?: Project; areas: Area[]; } const ProjectModal: React.FC = ({ isOpen, onClose, onSave, onDelete, project, areas, }) => { const [formData, setFormData] = useState( project || { name: '', description: '', area_id: null, active: true, } ); const modalRef = useRef(null); const [isClosing, setIsClosing] = useState(false); const [showConfirmDialog, setShowConfirmDialog] = useState(false); const { showSuccessToast, showErrorToast } = useToast(); useEffect(() => { if (project) { setFormData(project); } else { setFormData({ name: '', description: '', area_id: null, active: true, }); } }, [project]); useEffect(() => { const handleClickOutside = (event: MouseEvent) => { if ( modalRef.current && !modalRef.current.contains(event.target as Node) ) { handleClose(); } }; if (isOpen) { document.addEventListener('mousedown', handleClickOutside); } return () => { document.removeEventListener('mousedown', handleClickOutside); }; }, [isOpen]); // Handle Escape key to close modal useEffect(() => { const handleKeyDown = (event: KeyboardEvent) => { if (event.key === 'Escape') { handleClose(); } }; if (isOpen) { document.addEventListener('keydown', handleKeyDown); } return () => { document.removeEventListener('keydown', handleKeyDown); }; }, [isOpen]); const handleChange = ( e: React.ChangeEvent< HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement > ) => { const target = e.target; const { name, type } = target; if (type === 'checkbox') { const checked = (target as HTMLInputElement).checked; setFormData((prev) => ({ ...prev, [name]: checked, })); } else { const value = target.value; setFormData((prev) => ({ ...prev, [name]: value, })); } }; const handleSubmit = () => { onSave(formData); showSuccessToast( project ? 'Project updated successfully!' : 'Project created successfully!' ); handleClose(); }; const handleDeleteClick = () => { setShowConfirmDialog(true); }; const handleDeleteConfirm = () => { if (project && project.id && onDelete) { onDelete(project.id); showSuccessToast('Project deleted successfully!'); setShowConfirmDialog(false); handleClose(); } }; const handleClose = () => { setIsClosing(true); setTimeout(() => { onClose(); setIsClosing(false); }, 300); }; if (!isOpen) return null; return ( <>
{/* Project Name */}
{/* Description */}
{/* Area */}
{/* Active Checkbox */}
{/* Action Buttons */}
{project && onDelete && ( )}
{showConfirmDialog && ( setShowConfirmDialog(false)} /> )} ); }; export default ProjectModal;