/**
 * Retrieves the translation of text.
 *
 * @see https://developer.wordpress.org/block-editor/reference-guides/packages/packages-i18n/
 */
import { __ } from '@wordpress/i18n';

/**
 * Use Effect Hook
 */
import { useEffect } from '@wordpress/element';

/**
 * React hook that is used to mark the block wrapper element.
 * It provides all the necessary props like the class name.
 *
 * @see https://developer.wordpress.org/block-editor/reference-guides/packages/packages-block-editor/#useblockprops
 */
import { useBlockProps, InnerBlocks, MediaUpload, MediaUploadCheck } from '@wordpress/block-editor';
import { Button } from '@wordpress/components';

/**
 * Lets webpack process CSS, SASS or SCSS files referenced in JavaScript files.
 * Those files can contain any CSS code that gets applied to the editor.
 *
 * @see https://www.npmjs.com/package/@wordpress/scripts#using-css
 */
import './editor.scss';
import SidePanel from './side-panel';

/**
 * The edit function describes the structure of your block in the context of the
 * editor. This represents what the editor will render when the block is used.
 *
 * @see https://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/#edit
 *
 * @return {Element} Element to render.
 */
export default function Edit({ attributes, setAttributes }) {
  const { showImage, image, isCustomColor } = attributes;
  const blockProps = useBlockProps();

  // Ajout de la gestion des couleurs du thème
  const colors = window.OrphicWPColorsTheme || [];

  useEffect(() => {
    console.log("Initializing colors:", attributes.isFirstTimeChangeColor);
    if (attributes.isFirstTimeChangeColor) {
      // Essayer d'abord d'obtenir les couleurs depuis le thème
      let backgroundColor = '#ffffff';
      let textColor = '#172B4D';
      let borderColor = '#e0e0e0';
      
      if (colors && colors.length > 0) {
        backgroundColor = colors.find(c => c.slug === "background")?.color || backgroundColor;
        textColor = colors.find(c => c.slug === 'text')?.color || textColor;
        borderColor = colors.find(c => c.slug === 'border')?.color || borderColor;
      } else {
        // Utilisation des variables CSS si disponibles
        const computedStyle = getComputedStyle(document.documentElement);
        backgroundColor = computedStyle.getPropertyValue('--orphic-wp-block-plugin-color-background').trim() || backgroundColor;
        textColor = computedStyle.getPropertyValue('--orphic-wp-block-plugin-color-text').trim() || textColor;
        borderColor = computedStyle.getPropertyValue('--orphic-wp-block-plugin-color-border').trim() || borderColor;
      }

      console.log("Setting colors:", backgroundColor, textColor, borderColor);
      setAttributes({
        backgroundColor,
        textColor,
        borderColor,
        isFirstTimeChangeColor: false
      });
    }
  }, []);

  let style = {};
  if (isCustomColor) {
    style = {
      "--orphic-wp-testimonial-custom-background-color": attributes.backgroundColor,
      "--orphic-wp-testimonial-custom-text-color": attributes.textColor,
      "--orphic-wp-testimonial-custom-border-color": attributes.borderColor
    };
  }

  const onSelectImage = (media) => {
    setAttributes({
      image: {
        url: media.url,
        alt: media.alt,
        id: media.id,
      },
    });
  };

  return (
    <div {...blockProps}>
      <SidePanel attributes={attributes} setAttributes={setAttributes} />
      
      <div className={`testimonial-unit-content ${isCustomColor ? 'customColor' : ''}`} 
           style={style}>
        {showImage && (
          <div className="testimonial-image">
            <MediaUploadCheck>
              <MediaUpload
                onSelect={onSelectImage}
                allowedTypes={['image']}
                value={image?.id}
                render={({ open }) => (
                  <Button
                    onClick={open}
                    className={`image-button ${!image?.url ? 'is-empty' : ''}`}
                  >
                    {image?.url ? (
                      <img src={image.url} alt={image.alt} />
                    ) : (
                      '+'
                    )}
                  </Button>
                )}
              />
            </MediaUploadCheck>
          </div>
        )}
        <div className="testimonial-text">
          <InnerBlocks
            template={[
              ['core/paragraph', { placeholder: 'Add testimonial text...' }],
            ]}
          />
        </div>
        
       
      </div>
    </div>
  );
}
