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

/**
 * React hooks
 */
import { useRef, useMemo, useEffect, useState } from '@wordpress/element';

/**
 * WordPress components
 */
import { useBlockProps, InnerBlocks } from '@wordpress/block-editor';
import { Button } from '@wordpress/components';
import { useDispatch } from '@wordpress/data';

/**
 * Lets webpack process CSS, SASS or SCSS files referenced in JavaScript files.
 *
 * @see https://www.npmjs.com/package/@wordpress/scripts#using-css
 */
import './editor.scss';
import SidePanel from './side-panel';

const ALLOWED_BLOCKS = ['orphic-ui/carousel-slide'];
const TEMPLATE = [
  ['orphic-ui/carousel-slide'],
  ['orphic-ui/carousel-slide'],
  ['orphic-ui/carousel-slide']
];

/**
 * 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, clientId }) {
  const { slidesPerPage, autoWidth, slideWidth } = attributes;
  const sliderRef = useRef(null);
  const [align, setAlign] = useState("");
  const { insertBlock } = useDispatch('core/block-editor');

  const handleNext = () => {
    if (sliderRef.current) {
      const slideWidth = sliderRef.current.querySelector('.wp-block-orphic-ui-carousel-slide')?.offsetWidth || 0;
      sliderRef.current.scrollLeft += slideWidth + 20; // 20 is the gap
    }
  };

  const handlePrev = () => {
    if (sliderRef.current) {
      const slideWidth = sliderRef.current.querySelector('.wp-block-orphic-ui-carousel-slide')?.offsetWidth || 0;
      sliderRef.current.scrollLeft -= slideWidth + 20; // 20 is the gap
    }
  };

  const addNewSlide = () => {
    const block = wp.blocks.createBlock('orphic-ui/carousel-slide');
    insertBlock(block, undefined, clientId);
  };

  // Calcul de la largeur des slides en tenant compte du conteneur
  const calculatedWidth = useMemo(() => {
    if (!sliderRef.current) return autoWidth ? '50%' : `${slideWidth}px`;

    const sliderWidth = sliderRef.current.offsetWidth - 20; // 20px pour le padding (10px de chaque côté)
    
    if (!autoWidth) {
      return `${slideWidth}px`;
    }
    
    // Calcul basé sur la largeur réelle du slider
    return `calc((${sliderWidth}px - ${(slidesPerPage - 1) * 20}px) / ${slidesPerPage})`;
  }, [autoWidth, slideWidth, slidesPerPage, align]);

  // Mise à jour de la largeur lors du redimensionnement
  useEffect(() => {
    const handleResize = () => {
      // Force une mise à jour du calcul
      setAttributes({ ...attributes });
    };

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  const blockProps = useBlockProps({
    style: {
      '--slide-width': calculatedWidth
    }
  });

  useEffect(() => {
      setAlign(blockProps.className);
      console.log(calculatedWidth);
  }, [blockProps.className]);

  return (
    <div {...blockProps}>
      <SidePanel attributes={attributes} setAttributes={setAttributes} />
      
      <div className="orphic-ui-carousel">
        <div className="orphic-ui-carousel-container">
          <div className="orphic-ui-carousel-buttons">
            <button 
              className="orphic-ui-carousel-button prev" 
              onClick={handlePrev}
              aria-label="Previous slide"
            >
              ←
            </button>
            <button 
              className="orphic-ui-carousel-button next" 
              onClick={handleNext}
              aria-label="Next slide"
            >
              →
            </button>
          </div>

          <div className="orphic-ui-carousel-slider" ref={sliderRef}>
            <InnerBlocks 
              allowedBlocks={ALLOWED_BLOCKS}
              template={TEMPLATE}
              orientation="horizontal"
              templateLock={false}
              renderAppender={() => null}
            />
          </div>
        </div>
      </div>
      <Button
        className="add-slide-button"
        variant="primary"
        onClick={addNewSlide}
      >
        {__('Add slide', 'orphic-ui')}
      </Button>
    </div>
  );
}
