"use client"
import { useState } from "react"
import { useNavigate } from "react-router-dom"
import { Card, CardContent } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Label } from "@/components/ui/label"
import apiService from "@/services/apiService"
import { showSuccessToast, showErrorToast, showUpdateItemToast } from "@/utils/toast"
import { buildFormData } from "@/utils/formDataBuilder"
// Import hooks
import { useMigrantForm } from "@/hooks/useMigrantForm"
import { usePhotoManagement } from "@/hooks/usePhotoManagement"
import { useMigrantData } from "@/hooks/useMigrantData"
// Import components
import AddDialog from "./Modal/AddDialog"
import UpdateDialog from "./Modal/UpdateDialog"
// Import step components
import PersonDetailsStep from "./form-steps/PersonDetailsStep"
import MigrationInfoStep from "./form-steps/MigrationInfoStep"
import NaturalizationStep from "./form-steps/NaturalizationStep"
import ResidenceStep from "./form-steps/ResidenceStep"
import FamilyStep from "./form-steps/FamilyStep"
import InternmentStep from "./form-steps/InternmentStep"
import PhotosStep from "./form-steps/PhotosStep"
import ReviewStep from "./form-steps/ReviewStep"
import StepperHeader from "./form-steps/StepperHeader"
import StepperNavigation from "./form-steps/StepperNavigation"
const StepperForm = () => {
const navigate = useNavigate()
// Form state management
const {
formData,
setters,
resetForm,
populateFormData,
validation
} = useMigrantForm()
const photoManagement = usePhotoManagement()
const { loading, isEditMode, initialDataLoaded } = useMigrantData(
populateFormData,
photoManagement.populatePhotoData
)
// Local state
const [currentStep, setCurrentStep] = useState(0)
const [isAddDialogOpen, setIsAddDialogOpen] = useState(false)
const [isUpdateDialogOpen, setIsUpdateDialogOpen] = useState(false)
const [isSubmitting, setIsSubmitting] = useState(false)
const renderFormField = (
label: string,
value: string,
onChange: (value: string) => void,
type = "text",
placeholder?: string,
required?: boolean,
fieldPath?: string // Add this to identify the field for validation
) => {
const hasError = fieldPath ? validation.hasFieldError(fieldPath) : false
const errorMessage = fieldPath ? validation.getFieldError(fieldPath) : null
return (
{type === "textarea" ? (
)
}
const renderStepContent = () => {
switch (currentStep) {
case 0:
return
case 1:
return
case 2:
return
case 3:
return
case 4:
return
case 5:
return
case 6:
return (
)
case 7:
return (
)
default:
return null
}
}
const submitForm = async () => {
try {
const formDataToSubmit = buildFormData({
...formData,
photos: photoManagement.photos,
captions: photoManagement.captions,
mainPhotoIndex: photoManagement.mainPhotoIndex,
existingPhotos: photoManagement.existingPhotos,
removedPhotoIds: photoManagement.removedPhotoIds,
isEditMode,
})
if (isEditMode) {
const id = window.location.pathname.split('/').pop()
return await apiService.updateMigrant(parseInt(id!), formDataToSubmit)
} else {
return await apiService.createMigrant(formDataToSubmit)
}
} catch (error) {
throw error
}
}
const handleNext = () => {
// Validate current section before moving to next step
const sectionNames = ['person', 'migration', 'naturalization', 'residence', 'family', 'internment']
if (currentStep < sectionNames.length) {
const currentSection = sectionNames[currentStep] as 'person' | 'migration' | 'naturalization' | 'residence' | 'family' | 'internment'
const isValid = validation.validateSection(currentSection)
if (isValid || currentStep > 0) { // Allow moving forward from non-required sections
setCurrentStep(prev => prev + 1)
}
} else {
setCurrentStep(prev => prev + 1)
}
}
const handleSubmit = () => {
if (!isSubmitting) {
// Validate entire form before submitting
const isValid = validation.validateForm()
if (!isValid) {
showErrorToast("Please fix the errors in the form before submitting.")
return
}
if (isEditMode) {
setIsUpdateDialogOpen(true)
} else {
setIsAddDialogOpen(true)
}
}
}
const handleConfirmSubmit = async () => {
if (!isSubmitting) {
try {
setIsSubmitting(true)
await submitForm()
if (isEditMode) {
showUpdateItemToast(`Migrant ${formData.person.surname}, ${formData.person.christian_name}`, () => {
navigate(`/admin/migrants`)
})
} else {
showSuccessToast(() => {
navigate(`/admin/migrants`)
})
resetForm()
photoManagement.resetPhotos()
}
} catch (error) {
showErrorToast("There was a problem saving the migrant data. Please try again.")
} finally {
setIsSubmitting(false)
setIsAddDialogOpen(false)
setIsUpdateDialogOpen(false)
}
}
}
if (loading && isEditMode && !initialDataLoaded) {
return (
)
}
return (
{renderStepContent()}
{/* Display validation errors summary if any */}
{Object.keys(validation.validationErrors).length > 0 && (
Please fix the following errors:
{Object.entries(validation.validationErrors).map(([field, error]) => (
- • {error}
))}
)}
setCurrentStep(prev => prev - 1)}
onNext={handleNext}
onSubmit={handleSubmit}
/>
)
}
export default StepperForm