import { useCallback, useEffect, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { toast } from 'sonner'; import PrimaryButton from '../../../components/button/PrimaryButton'; import EditCard from '../../../components/card/EditCard'; import SimpleInput from '../../../components/input/SimpleInput'; import { createCustomSection, getCustomSections, updateCustomSection, } from '../../../services/data'; import SectionList from './SectionList'; export const CustomSections: React.FC = () => { const { t } = useTranslation(); const [newSection, setNewSection] = useState(''); const [newField, setNewField] = useState(''); const [newIcon, setNewIcon] = useState(''); const [sections, setSections] = useState< { name: string; field: string; icon?: string }[] >([]); const [loading, setLoading] = useState(true); const [isEditing, setIsEditing] = useState(false); const [error, setError] = useState(null); useEffect(() => { const fetchSections = async () => { try { const data = await getCustomSections(); setSections(data.datas); setLoading(false); } catch (err) { setError('Error fetching sections'); setLoading(false); } }; void fetchSections(); }, [isEditing]); const handleAddSection = async () => { let resp: { datas: { name: string; field: string; icon?: string }; status?: string; }; try { resp = await createCustomSection({ name: newSection, field: newField, icon: newIcon, }); } catch (error) { setError('Error creating section'); toast.error(t('err.errorCreatingSection')); setNewSection(''); setNewField(''); setNewIcon(''); return; } toast.success(t('msg.sectionCreatedOk')); setNewSection(''); setNewField(''); setNewIcon(''); setSections(prevSections => [ ...prevSections, { icon: resp.datas.icon, field: resp.datas.field, name: resp.datas.name }, ]); }; /** * Lógica para hacer uptdate (PUT) * de los lenguajes. */ const [newSectionList, setNewSectionList] = useState< { name: string; field: string; icon?: string }[] >([]); const handleUpdateSectionList = useCallback( (data: { name: string; field: string; icon: string }[]) => { setNewSectionList(data); }, [setNewSectionList], ); const onClickSave = async () => { try { await updateCustomSection(newSectionList); setIsEditing(false); toast.success(t('msg.sectionUpdateOk')); } catch (error) { setError('Error updating sections'); toast.error(t('err.errorUpdatingSections')); return; } }; useEffect(() => { error && console.error(error); }, [error]); return (
{/* TODO: Alinear bien los inputs */} {newIcon ? ( newIcon.startsWith('fa-') ? ( ) : ( {newIcon} ) ) : null}
{t('btn.create')}
setIsEditing(false)} onClickEdit={() => setIsEditing(true)} onClickSave={onClickSave} title={t('listOfSections')} > {loading ? (

{t('loading')}

) : ( ({ ...section, icon: section.icon ?? '', _id: index.toString(), }))} isDisabled={!isEditing} onUpdateList={handleUpdateSectionList} setSections={setSections} /> )}
); };