import React, { useState, useEffect } from 'react'; import axios from 'axios'; import { toast } from 'sonner'; import { useTranslation } from 'react-i18next'; import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'; import { X } from 'lucide-react'; const API_URL = '/api'; export function ItemModal({ item, onClose, onSaved, open, categories = [] }) { const { t } = useTranslation(); const [formData, setFormData] = useState({ url: '', name: '', target_price: '', tags: '', description: '', notification_channel_id: 'none', category: '' }); const [channels, setChannels] = useState([]); const [showCustomInput, setShowCustomInput] = useState(false); useEffect(() => { const fetchChannels = async () => { try { const response = await axios.get(`${API_URL}/notifications/channels`); setChannels(response.data.filter(c => c.is_active)); } catch (error) { console.error('Error fetching channels:', error); } }; if (open) { fetchChannels(); } }, [open]); useEffect(() => { if (item) { setFormData({ url: item.url || '', name: item.name || '', target_price: item.target_price || '', tags: item.tags || '', description: item.description || '', notification_channel_id: item.notification_channel_id ? item.notification_channel_id.toString() : 'none', category: item.category || '' }); setShowCustomInput(!!item.category && !categories.includes(item.category)); } else { setFormData({ url: '', name: '', target_price: '', tags: '', description: '', notification_channel_id: 'none', category: '' }); setShowCustomInput(false); } }, [item, open, categories]); const handleSubmit = async (e) => { e.preventDefault(); try { const payload = { ...formData, target_price: formData.target_price ? parseFloat(formData.target_price) : null, notification_channel_id: formData.notification_channel_id === 'none' ? null : parseInt(formData.notification_channel_id) }; if (item) { await axios.put(`${API_URL}/items/${item.id}`, payload); toast.success(t('toast.itemUpdated')); } else { await axios.post(`${API_URL}/items`, payload); toast.success(t('toast.itemCreated')); } onSaved(); onClose(); } catch (error) { console.error('Error saving item:', error); toast.error(t('toast.itemError')); } }; return ( {item ? t('itemModal.editTitle') : t('itemModal.addTitle')}
setFormData({ ...formData, url: e.target.value })} />
setFormData({ ...formData, name: e.target.value })} />
setFormData({ ...formData, target_price: e.target.value })} />
{showCustomInput ? (
setFormData({ ...formData, category: e.target.value })} autoFocus />
) : ( )}
setFormData({ ...formData, tags: e.target.value })} />