import React, { useState } from 'react'; import { CreateButtonProps } from '../ButtonTypes'; import Button from '../Button'; import { Popup, EditForm } from '../../Popup'; import { useLanguage } from '../../../../contexts/LanguageContext'; const CreateButton: React.FC = ({ onCreate, fields, popupTitle = 'Create New Item', popupSize = 'medium', disabled = false, loading = false, className = '', children, icon, iconPosition = 'left', variant = 'primary', size = 'md', onSuccess, onError, ...props }) => { const { t } = useLanguage(); const [isCreating, setIsCreating] = useState(false); const [isPopupOpen, setIsPopupOpen] = useState(false); const [formData, setFormData] = useState({}); // Initialize form data with default values React.useEffect(() => { const initialData: any = {}; fields.forEach(field => { initialData[field.key] = field.defaultValue || ''; }); setFormData(initialData); }, [fields]); const handleButtonClick = () => { if (!disabled && !loading && !isCreating) { // Reset form data const initialData: any = {}; fields.forEach(field => { initialData[field.key] = field.defaultValue || ''; }); setFormData(initialData); setIsPopupOpen(true); } }; const handleSave = async (updatedData: any) => { setIsCreating(true); try { const result = await onCreate(updatedData); if (result?.success !== false) { // Success setIsPopupOpen(false); if (onSuccess) { onSuccess(result); } } else { // Handle error if (onError) { onError(result?.error || 'Creation failed'); } } } catch (error: any) { console.error('Creation failed:', error); if (onError) { onError(error.message || 'Creation failed'); } } finally { setIsCreating(false); } }; const handleCancel = () => { setIsPopupOpen(false); }; const isDisabled = disabled || loading || isCreating; // Resolve language text for popup title const resolvedPopupTitle = typeof popupTitle === 'string' ? t(popupTitle, popupTitle) : popupTitle; // Resolve language text for fields const resolvedFields = fields.map(field => ({ ...field, label: typeof field.label === 'string' ? t(field.label, field.label) : field.label, placeholder: field.placeholder ? (typeof field.placeholder === 'string' ? t(field.placeholder, field.placeholder) : field.placeholder) : undefined, editable: true })); return ( <> {/* Create Popup */} ); }; export default CreateButton;