import React, { useState, useEffect, useCallback } from 'react'; import { View, Text, TouchableOpacity, TextInput } from 'react-native'; import { Plus, Trash2, CheckCircle2 } from 'lucide-react-native'; import GenericDropdown from './GenericDropdown'; import api from '@/utils/api'; import { useAlert } from './AlertComponent'; interface LaborItem { id_registry: number; id_user: number | null; name: string; hours: string | number; minutes: string | number; sync?: boolean; id?: number; } interface ActivityLaborCardProps { title: string; fetchUrl: string; laborList: LaborItem[]; onAddLabor: (labor: LaborItem) => void; onRemoveLabor: (index: number) => void; } export default function ActivityLaborCard({ title, fetchUrl, laborList, onAddLabor, onRemoveLabor }: ActivityLaborCardProps) { const alert = useAlert(); const [items, setItems] = useState([]); const [showInput, setShowInput] = useState(false); // Form states const [selectedId, setSelectedId] = useState(null); const [hours, setHours] = useState(''); const [minutes, setMinutes] = useState(''); const loadItems = useCallback(async () => { try { const res = await api.get(fetchUrl); if (res.data?.success && res.data.items) { // Map the items to include an 'id' property required by GenericDropdown const mappedItems = res.data.items.map((item: any) => ({ ...item, id: item.id_registry })); setItems(mappedItems); } } catch (error) { console.error('Error fetching labor items:', error); } }, [fetchUrl]); useEffect(() => { loadItems(); }, [loadItems]); const handleAdd = () => { if (!selectedId) { alert.showAlert('error', 'Attenzione', 'Selezionare un elemento dalla lista'); return; } if (hours === '' && minutes === '') { alert.showAlert('error', 'Attenzione', 'Inserire le ore o i minuti di lavoro'); return; } const el = items.find(data => data.id_registry === selectedId); if (el) { const newLabor: LaborItem = { id_registry: selectedId, id_user: el.id_user, name: el.label, hours: hours === '' ? '0' : hours, minutes: minutes === '' ? '0' : minutes, }; onAddLabor(newLabor); // Reset and hide setSelectedId(null); setHours(''); setMinutes(''); setShowInput(false); } }; const toggleInput = () => { setSelectedId(null); setHours(''); setMinutes(''); setShowInput(!showInput); }; return ( {title} {showInput ? 'Annulla' : 'Aggiungi'} {showInput && ( setSelectedId(id as number)} placeholder="Seleziona..." searchPlaceholder="Cerca per nome" /> )} {laborList.map((item, index) => ( {item.name} {item.hours}h {item.minutes}m {item.sync ? ( ) : ( onRemoveLabor(index)} className="w-8 items-center justify-center" > )} ))} {laborList.length === 0 && !showInput && ( Nessun elemento inserito )} ); }