import { ProfilesAction } from '@/components/Settings/Profiles/actions/ProfilesAction'; import { ProfileContext } from '@/contexts/ProfileContext'; import { Box, Button, MenuItem, Paper, Select, SelectChangeEvent, Stack, Table, TableBody, TableCell, TableHead, TableRow } from '@mui/material'; import { nanoid } from 'nanoid'; import { useCallback, useContext, useEffect, useRef, useState } from 'react'; import { Item, Items, Profiles } from '../../../../data/types'; import CreateItemDialog from '../CreateItem/CreateItemDialog'; import ItemDialog from '../ItemDialog/ItemDialog'; import { ItemsTableAction } from './actions/ItemsTableAction'; import ItemsTableRow from './ItemsTableRow'; export default function ItemsTable() { const [items, setItems] = useState([]); const [take, setTake] = useState(20); const tableRef = useRef(null); const [openCreateDialog, setOpenCreateDialog] = useState(false); const [openItemDialog, setOpenItemDialog] = useState(false); const [formKey, setFormKey] = useState(() => nanoid()); const [profiles, setProfiles] = useState([]); const { profile, setProfile } = useContext(ProfileContext); const [currentItem, setCurrentItem] = useState(null); const handleUpdateProfiles = useCallback(async () => { const updatedProfiles = await ProfilesAction(); setProfiles(updatedProfiles); }, []); useEffect(() => { handleUpdateProfiles(); }, [handleUpdateProfiles]); const handleUpdateItems = useCallback( async (id: string) => { try { const updatedItems = await ItemsTableAction({ take, profile: id }); setItems(updatedItems); } catch (error) { console.error("Couldn't fetch items."); } }, [take] ); const handleFetchItems = useCallback( (event: SelectChangeEvent) => { handleUpdateItems(event.target.value); setFormKey(nanoid()); setProfile(event.target.value); }, [handleUpdateItems, setProfile] ); useEffect(() => { if (profile) { handleUpdateItems(profile); setFormKey(nanoid()); } }, [profile, handleUpdateItems]); useEffect(() => { const handleScroll = (event: Event) => { const target = event.target as HTMLDivElement; const bottom = target.scrollHeight - target.scrollTop === target.clientHeight; if (bottom) { setTake((prevTake) => prevTake + 20); } }; const tableElement = tableRef.current; if (tableElement) { tableElement.addEventListener('scroll', handleScroll); return () => { tableElement.removeEventListener('scroll', handleScroll); }; } }, [take]); const handleCreateItemDialog = () => { setOpenCreateDialog(true); }; const handleCloseCreateDialog = async (created: boolean) => { setFormKey(nanoid()); setOpenCreateDialog(false); if (created) { const updatedItems = await ItemsTableAction({ take, profile }); setItems(updatedItems); } }; const handleOpenItemDialog = (item: Item) => { setCurrentItem(item); setOpenItemDialog(true); }; const handleCloseItemDialog = async () => { setOpenItemDialog(false); }; return ( {profiles.length > 0 && ( )} Name Description Price Currency Tag Date {items && items.map((item) => ( ))}
{currentItem && ( )}
); }