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<CreateButtonProps> = ({
  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<any>({});

  // 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 (
    <>
      <Button
        {...props}
        variant={variant}
        size={size}
        disabled={isDisabled}
        loading={false}
        className={`createButton ${className}`}
        onClick={handleButtonClick}
        icon={isCreating ? undefined : icon}
        iconPosition={iconPosition}
      >
        {isCreating && (
          <div className="spinnerIcon" style={{ marginRight: '8px' }} />
        )}
        {children || (isCreating ? t('common.creating', 'Creating...') : t('common.create', 'Create'))}
      </Button>

      {/* Create Popup */}
      <Popup
        isOpen={isPopupOpen}
        title={resolvedPopupTitle}
        onClose={handleCancel}
        size={popupSize}
        closable={!isCreating}
      >
        <EditForm
          data={formData}
          fields={resolvedFields}
          onSave={handleSave}
          onCancel={handleCancel}
          saveButtonText={t('common.create', 'Create')}
          cancelButtonText={t('common.cancel', 'Cancel')}
        />
      </Popup>
    </>
  );
};

export default CreateButton;

