import React from 'react';
import FormField from '../ui/FormField';
import { useForm } from '../../hooks/useForm';
/**
* A form component for creating or updating a shift.
* It uses the `useForm` hook for form state management and validation.
*
* @param {object} props - The component props.
* @param {object} [props.initialData] - Initial data to pre-fill the form (for editing).
* @param {function} props.onSubmit - Function to call when the form is submitted and validated.
* @param {function} props.onCancel - Function to call when the cancel button is clicked.
* @param {boolean} [props.loading=false] - Indicates if the form is currently submitting.
**/
const ShiftForm = ({ initialData, onSubmit, onCancel, loading }) => {
const { values, errors, handleChange, handleBlur, validate } = useForm(
initialData || {
name: '',
start_time: '',
end_time: '',
description: '',
},
{
name: { required: true, minLength: 2 },
start_time: { required: true },
end_time: { required: true },
}
);
/**
* Handles the form submission. Prevents default form submission and calls the onSubmit prop
* if the form data is valid.
* @param {Event} e - The form submission event.
*/
const handleSubmit = (e) => {
e.preventDefault();
if (validate()) {
onSubmit(values);
}
};
return (
<form onSubmit={handleSubmit} className="space-y-4">
<FormField
label="Shift Name"
name="name"
value={values.name}
onChange={handleChange}
onBlur={handleBlur}
error={errors.name}
required
/>
<div className="grid grid-cols-2 gap-4">
<FormField
label="Start Time"
name="start_time"
type="time"
value={values.start_time}
onChange={handleChange}
onBlur={handleBlur}
error={errors.start_time}
required
/>
<FormField
label="End Time"
name="end_time"
type="time"
value={values.end_time}
onChange={handleChange}
onBlur={handleBlur}
error={errors.end_time}
required
/>
</div>
<FormField
label="Description"
name="description"
type="textarea"
value={values.description}
onChange={handleChange}
onBlur={handleBlur}
error={errors.description}
placeholder="Enter shift description..."
/>
<div className="flex justify-end space-x-2 pt-4">
<button
type="button"
onClick={onCancel}
className="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-200 rounded-md hover:bg-gray-300"
disabled={loading}
>
Cancel
</button>
<button
type="submit"
className="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-md hover:bg-blue-700 disabled:opacity-50"
disabled={loading}
>
{loading ? 'Saving...' : initialData ? 'Update' : 'Create'}
</button>
</div>
</form>
);
};
export default ShiftForm;
Source