import React, { useState, useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; import { appointmentService } from '../../services/appointmentService'; import { patientService } from '../../services/patientService'; import { doctorService } from '../../services/doctorService'; import ErrorAlert from '../../components/ErrorAlert'; import SuccessAlert from '../../components/SuccessAlert'; function AppointmentForm() { const navigate = useNavigate(); const user = JSON.parse(localStorage.getItem('user') || '{}'); const isPatient = user.role === 'PATIENT'; const isDoctor = user.role === 'DOCTOR'; const [formData, setFormData] = useState({ patientId: isPatient ? (user.patientId || '') : '', doctorId: isDoctor ? (user.doctorId || '') : '', appointmentDate: '', appointmentTime: '', }); const [patients, setPatients] = useState([]); const [doctors, setDoctors] = useState([]); const [error, setError] = useState(null); const [success, setSuccess] = useState(null); const [loading, setLoading] = useState(false); useEffect(() => { fetchData(); }, []); const fetchData = async () => { try { // For patients, we don't need to fetch all patients if (!isPatient) { const patientsRes = await patientService.getAllPatients(); setPatients(patientsRes.data); } const doctorsRes = await doctorService.getAllDoctors(); setDoctors(doctorsRes.data); } catch (err) { setError('Failed to fetch doctors'); } }; const handleChange = (e) => { const { name, value } = e.target; setFormData(prev => ({ ...prev, [name]: value })); }; const handleSubmit = async (e) => { e.preventDefault(); if (!formData.patientId || !formData.doctorId || !formData.appointmentDate || !formData.appointmentTime) { setError('Please fill in all required fields'); return; } try { setLoading(true); await appointmentService.createAppointment({ patientId: parseInt(formData.patientId), doctorId: parseInt(formData.doctorId), appointmentDate: formData.appointmentDate, appointmentTime: formData.appointmentTime, }); setSuccess('Appointment created successfully!'); setTimeout(() => navigate('/appointments'), 1500); } catch (err) { setError(err.response?.data?.error || 'Failed to create appointment'); } finally { setLoading(false); } }; return (

Create Appointment

{error && setError(null)} />} {success && setSuccess(null)} />}
{isPatient ? (

Patient: {user.firstName} {user.lastName} ({user.username})

) : (
)} {isDoctor ? (

Dr. {user.firstName} {user.lastName}

) : (
)}
); } export default AppointmentForm;