"use client" import type React from "react" import { useState, useCallback, useMemo } from "react" interface PatientRecord { id: string fullName: string contactNumber: string cityLocation: string stateRegion: string lastVisitDate: string nextAppointmentDate: string createdAt: string updatedAt: string } interface NotificationState { message: string type: "success" | "error" | "info" isVisible: boolean } interface FormData { fullName: string contactNumber: string cityLocation: string stateRegion: string lastVisitDate: string nextAppointmentDate: string } const useLocalStorage = (key: string, initialValue: T) => { const [storedValue, setStoredValue] = useState(() => { if (typeof window === "undefined") return initialValue try { const item = window.localStorage.getItem(key) return item ? JSON.parse(item) : initialValue } catch (error) { console.error(`Error reading localStorage key "${key}":`, error) return initialValue } }) const setValue = useCallback( (value: T | ((val: T) => T)) => { try { const valueToStore = value instanceof Function ? value(storedValue) : value setStoredValue(valueToStore) if (typeof window !== "undefined") { window.localStorage.setItem(key, JSON.stringify(valueToStore)) } } catch (error) { console.error(`Error setting localStorage key "${key}":`, error) } }, [key, storedValue], ) return [storedValue, setValue] as const } const useNotification = () => { const [notification, setNotification] = useState({ message: "", type: "info", isVisible: false, }) const showNotification = useCallback((message: string, type: NotificationState["type"] = "info") => { setNotification({ message, type, isVisible: true }) setTimeout(() => { setNotification((prev) => ({ ...prev, isVisible: false })) }, 4000) }, []) return { notification, showNotification } } const generatePatientId = (): string => { return `PT${Date.now().toString().slice(-6)}${Math.random().toString(36).substr(2, 3).toUpperCase()}` } const formatDateDisplay = (dateString: string): string => { if (!dateString) return "Não informado" try { const date = new Date(dateString) return date.toLocaleDateString("pt-BR", { day: "2-digit", month: "2-digit", year: "numeric", }) } catch { return "Data inválida" } } const validateFormData = (data: FormData): string[] => { const errors: string[] = [] if (!data.fullName.trim()) errors.push("Nome completo é obrigatório") if (!data.contactNumber.trim()) errors.push("Número de contato é obrigatório") if (!data.cityLocation.trim()) errors.push("Cidade é obrigatória") if (data.fullName.trim().length < 2) errors.push("Nome deve ter pelo menos 2 caracteres") if (data.contactNumber.trim().length < 10) errors.push("Número de contato deve ter pelo menos 10 dígitos") return errors } export default function HospitalManagementSystem() { const [patientRecords, setPatientRecords] = useLocalStorage("hospital_patients_v3", []) const [isModalOpen, setIsModalOpen] = useState(false) const [editingRecord, setEditingRecord] = useState(null) const [formData, setFormData] = useState({ fullName: "", contactNumber: "", cityLocation: "", stateRegion: "", lastVisitDate: "", nextAppointmentDate: "", }) const { notification, showNotification } = useNotification() const systemMetrics = useMemo( () => ({ totalPatients: patientRecords.length, scheduledAppointments: patientRecords.filter((record) => record.nextAppointmentDate).length, contactsAvailable: patientRecords.filter((record) => record.contactNumber).length, recentVisits: patientRecords.filter((record) => { if (!record.lastVisitDate) return false const visitDate = new Date(record.lastVisitDate) const thirtyDaysAgo = new Date() thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30) return visitDate >= thirtyDaysAgo }).length, }), [patientRecords], ) const resetFormState = useCallback(() => { setFormData({ fullName: "", contactNumber: "", cityLocation: "", stateRegion: "", lastVisitDate: "", nextAppointmentDate: "", }) setEditingRecord(null) setIsModalOpen(false) }, []) const handleInputChange = useCallback((field: keyof FormData, value: string) => { setFormData((prev) => ({ ...prev, [field]: value })) }, []) const openCreateModal = useCallback(() => { resetFormState() setIsModalOpen(true) }, [resetFormState]) const openEditModal = useCallback((record: PatientRecord) => { setFormData({ fullName: record.fullName, contactNumber: record.contactNumber, cityLocation: record.cityLocation, stateRegion: record.stateRegion, lastVisitDate: record.lastVisitDate, nextAppointmentDate: record.nextAppointmentDate, }) setEditingRecord(record) setIsModalOpen(true) }, []) const handleSubmitForm = useCallback( (e: React.FormEvent) => { e.preventDefault() const validationErrors = validateFormData(formData) if (validationErrors.length > 0) { showNotification(validationErrors[0], "error") return } const timestamp = new Date().toISOString() if (editingRecord) { const updatedRecord: PatientRecord = { ...editingRecord, ...formData, updatedAt: timestamp, } setPatientRecords((prev) => prev.map((record) => (record.id === editingRecord.id ? updatedRecord : record))) showNotification("Dados do paciente atualizados com sucesso!", "success") } else { const newRecord: PatientRecord = { id: generatePatientId(), ...formData, createdAt: timestamp, updatedAt: timestamp, } setPatientRecords((prev) => [...prev, newRecord]) showNotification("Paciente cadastrado no sistema!", "success") } resetFormState() }, [formData, editingRecord, setPatientRecords, showNotification, resetFormState], ) const handleDeleteRecord = useCallback( (recordId: string) => { const confirmDelete = window.confirm( "Confirma a remoção deste paciente do sistema? Esta ação não pode ser desfeita.", ) if (confirmDelete) { setPatientRecords((prev) => prev.filter((record) => record.id !== recordId)) showNotification("Paciente removido do sistema.", "success") } }, [setPatientRecords, showNotification], ) return (

MedSystem Pro

Sistema Integrado de Gestão Hospitalar

Dr. Admin

{systemMetrics.totalPatients}

Total de Pacientes

{systemMetrics.scheduledAppointments}

Consultas Agendadas

{systemMetrics.contactsAvailable}

Contatos Disponíveis

{systemMetrics.recentVisits}

Visitas Recentes

Registro de Pacientes

Pacientes Cadastrados {patientRecords.length}

{patientRecords.length === 0 ? (

Nenhum paciente cadastrado

Clique em "Novo Paciente" para começar

) : (
{patientRecords.map((record) => ( ))}
Paciente Contato Localização Última Consulta Próxima Consulta Ações
{record.fullName}
ID: {record.id}
{record.contactNumber}
{record.cityLocation} {record.stateRegion && `, ${record.stateRegion}`}
Última
{formatDateDisplay(record.lastVisitDate)}
Próxima
{formatDateDisplay(record.nextAppointmentDate)}
)}
🏥 MedSystem Pro - Sistema Hospitalar Integrado
Versão 2.1.0 | Desenvolvido com React & TypeScript
{isModalOpen && (
e.target === e.currentTarget && resetFormState()}>

{editingRecord ? "Editar Paciente" : "Novo Paciente"}

handleInputChange("fullName", e.target.value)} placeholder="Nome completo do paciente" required />
handleInputChange("contactNumber", e.target.value)} placeholder="(11) 99999-9999" required />
handleInputChange("cityLocation", e.target.value)} placeholder="Cidade" required />
handleInputChange("stateRegion", e.target.value)} placeholder="SP, RJ, MG..." />
handleInputChange("lastVisitDate", e.target.value)} />
handleInputChange("nextAppointmentDate", e.target.value)} />
)} {notification.isVisible && (
{notification.message}
)}
) }