'use client'; import React, { useState } from 'react'; import { Career } from '@/app/types'; import { apiClient } from '@/app/utils/apiClient'; import { TextField, Button, Box, FormControl, FormControlLabel, RadioGroup, Radio, Paper, Typography, CircularProgress } from '@mui/material'; interface CareerFormProps { initialData?: Career; onSubmitSuccess: () => void; onCancel: () => void; } const CareerForm: React.FC = ({ initialData, onSubmitSuccess, onCancel }) => { const [formData, setFormData] = useState>( initialData || { title: '', description: '', location: '', salary: '', status: 'active' } ); const [errors, setErrors] = useState>({}); const [loading, setLoading] = useState(false); const handleChange = (e: React.ChangeEvent) => { const { name, value } = e.target; setFormData(prev => ({ ...prev, [name]: value })); // Clear error when user types if (errors[name]) { setErrors(prev => { const newErrors = { ...prev }; delete newErrors[name]; return newErrors; }); } }; const validate = (): boolean => { const newErrors: Record = {}; if (!formData.title?.trim()) { newErrors.title = 'Job title is required'; } else if (formData.title.length < 3) { newErrors.title = 'Job title must be at least 3 characters'; } if (!formData.description?.trim()) { newErrors.description = 'Job description is required'; } else if (formData.description.length < 50) { newErrors.description = 'Job description must be at least 50 characters'; } if (!formData.location?.trim()) { newErrors.location = 'Job location is required'; } setErrors(newErrors); return Object.keys(newErrors).length === 0; }; const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); if (!validate()) return; setLoading(true); try { if (initialData?.id) { // Update existing career await apiClient(`/careers/update/${initialData.id}`, { method: 'PUT', body: JSON.stringify(formData) }); } else { // Create new career await apiClient('/careers/create', { method: 'POST', body: JSON.stringify(formData) }); } onSubmitSuccess(); } catch (error) { console.error('Error saving career:', error); setErrors({ submit: 'Failed to save job listing. Please try again.' }); } finally { setLoading(false); } }; return ( {initialData ? 'Edit Job Listing' : 'Create New Job Listing'} Status } label="Active" /> } label="Inactive" /> {errors.submit && ( {errors.submit} )} ); }; export default CareerForm;