import { useState } from 'react';
import FilerobotImageEditor from 'react-filerobot-image-editor';

export function PhotoPreEditor({ imageSrc, onComplete, onClose }) {
  const [saving, setSaving] = useState(false);

  const handleComplete = (editedImageObject, designState) => {
    setSaving(true);

    // Export the edited image
    editedImageObject.exportAsync({
      quality: 1,
      mimeType: 'image/png',
    }).then((blob) => {
      const url = URL.createObjectURL(blob);
      setSaving(false);
      onComplete(url);
    }).catch((error) => {
      console.error('Export failed:', error);
      setSaving(false);
      onClose();
    });
  };

  return (
    <div className="filerobot-overlay">
      <div className="filerobot-container">
        <FilerobotImageEditor
          source={imageSrc}
          onSave={handleComplete}
          onClose={onClose}
          annotationsCommon={{
            fill: '#ff0000',
            stroke: '#000000',
            strokeWidth: 0,
          }}
          annotations={[
            'Text',
            'Rectangle',
            'Ellipse',
            'Line',
            'Pen',
            'Eraser',
          ]}
          tabs={['adjust', 'filters', 'finetune', 'annotate', 'watermark']}
          defaultTabId="adjust"
          theme={{
            accentColor: '#38bdf8',
            palettePrimary: '#38bdf8',
          }}
          saveButtonProps={{
            label: saving ? 'Exporting...' : 'Use Edited Image',
          }}
        />
      </div>
    </div>
  );
}
