import React, { useCallback, useEffect, useRef, useState } from 'react'; import { useManageMunicipiosContext } from '../hooks/useManageMunicipiosContext'; import { Alert, useDataGrid } from '@/components'; import axios from 'axios'; import { apiConfig } from '@/config/api.config'; import { toast } from 'sonner'; import { Dialog, DialogBody, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'; import { Input } from '@/components/ui/input'; import { Button } from '@/components/ui/button'; import { getAuth, useAuthContext } from '@/auth'; import { useCallApi } from '@/hooks'; import { doSaveLogActivity } from '@/actions/GlobalActions'; import { RefreshCw } from 'lucide-react'; const API_URL = apiConfig.service_master_data; const EditDialog = () => { const { showEditDialog, handleEditDialog, selectedMunicipios, municipios } = useManageMunicipiosContext(); const { reload } = useDataGrid(); const { PutData, GetData } = useCallApi(); const parsedUser = getAuth()?.user; const [isLoading, setIsLoading] = useState(false); const [isSubmitting, setIsSubmitting] = useState(false); const [alert, setAlert] = useState({ show: false, message: '' }); const initialState = { name: '', updated_by: '', updated_at: '' }; const [formField, setFormField] = useState(initialState); const created_time = new Date(); const formattedTime = created_time.toISOString().slice(0, 19).replace('T', ' '); const [errors, setErrors] = useState>({}); const resetForm = () => { setFormField(initialState); setErrors({}); }; const validateForm = () => { const requiredFields = [{ key: 'name', label: 'Municipio Name' }]; const newErrors: Record = {}; let isValid = true; requiredFields.forEach(({ key, label }) => { if ( formField[key as keyof typeof formField] === '' || formField[key as keyof typeof formField] === null || formField[key as keyof typeof formField] === undefined ) { newErrors[key] = `${label} is required`; toast.error(`${label} is required`); isValid = false; } }); setErrors(newErrors); return isValid; }; const doUpdateMunicipios = useCallback( async (e: React.FormEvent) => { e.preventDefault(); setIsSubmitting(true); try { const response = await PutData( `${API_URL}/municipios/update/${selectedMunicipios}`, formField ); if (response?.status) { handleEditDialog(false, null); resetForm(); toast.success('Success update municipio'); reload(); const createActivity = { module: 'Manage Municipios', description: `Edit Municipio => ${selectedMunicipios}`, action: 'U' }; doSaveLogActivity(createActivity); } else { toast.error('Failed update municipios'); setAlert({ show: true, message: response?.message }); } } catch (error) { toast.error('Something went wrong, please try again.'); } finally { setIsSubmitting(false); } }, [selectedMunicipios, formField] ); const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); setIsSubmitting(true); if(!validateForm()) { setIsSubmitting(false); return; } doUpdateMunicipios(e); // console.log(parsedUser.email); // console.log(formField); // setAlert({ show: false, message: '' }); }; const doFetchData = useCallback(async (id: string) => { setIsLoading(true); const minDelay = new Promise((resolve) => setTimeout(resolve, 300)); const fetchData = GetData(`${API_URL}/municipios/getdata/${id}`, { id }); const [response] = await Promise.all([fetchData, minDelay]); if (response?.status) { setFormField((prev) => ({ ...prev, name: response.data.name })); } else { setFormField((prev) => ({ ...prev, name: '' })); } setIsLoading(false); }, []); // const handleUpdate = (e: React.FormEvent) => { // e.preventDefault(); // if (formField.name.trim() === '') { // setAlert({ show: true, message: 'Please fill name field.' }); // return; // } // doUpdateMunicipios(e); // console.log(formField); // setAlert({ show: false, message: '' }); // }; useEffect(() => { if (selectedMunicipios) { doFetchData(selectedMunicipios); } }, [selectedMunicipios]); useEffect(() => { if (showEditDialog === false) { resetForm(); } }, [showEditDialog]); useEffect(() => { if (selectedMunicipios) { setFormField({ name: formField.name, updated_by: parsedUser.email, updated_at: formattedTime }); } }, [formattedTime]); // console.log(selectedMunicipios); return ( handleEditDialog(open, null)}> Municipio - Update
{alert.show && (

{alert.message}

)} {isLoading ? (

Loading Municipio Details...

) : (
{ setFormField((prev) => ({ ...prev, name: target.value })); if (target.value) { setErrors((prev) => ({ ...prev, name: '' })); } }} /> {errors.name && ( {errors.name} )}
)}
); }; export default EditDialog;