import { __ } from '@wordpress/i18n';
import { useBlockProps, InspectorControls } from '@wordpress/block-editor';
import { PanelBody, TextControl } from '@wordpress/components';
import './editor.scss';

export default function Edit({ attributes, setAttributes }) {
  const { categories, description } = attributes;

  const updateCategoryTitle = (index, value) => {
    const updatedCategories = [...categories];
    updatedCategories[index].title = value;
    setAttributes({ categories: updatedCategories });
  };

  const updateCategoryImageUrl = (index, value) => {
    const updatedCategories = [...categories];
    updatedCategories[index].imageUrl = value;
    setAttributes({ categories: updatedCategories });
  };

  return (
    <div {...useBlockProps()}>
      <InspectorControls>
        <PanelBody title={__('Session Categories Settings', 'session-categories')}>
          {categories.map((category, index) => (
            <div key={index} style={{ marginBottom: '20px' }}>
              <TextControl
                label={__('Category Title', 'session-categories')}
                value={category.title}
                onChange={(value) => updateCategoryTitle(index, value)}
              />
              <TextControl
                label={__('Category Image URL', 'session-categories')}
                value={category.imageUrl}
                onChange={(value) => updateCategoryImageUrl(index, value)}
              />
            </div>
          ))}
          <TextControl
            label={__('Description', 'session-categories')}
            value={description}
            onChange={(value) => setAttributes({ description: value })}
          />
        </PanelBody>
      </InspectorControls>

      <section className="session-categories">
        <div className="session-categories__grid">
          {categories.map((category, index) => (
            <div key={index} className="session-card">
              <img
                className="session-card__image"
                src={category.imageUrl}
                alt={category.alt}
              />
              <div className="session-card__overlay">
                <h3 className="session-card__title">{category.title}</h3>
              </div>
            </div>
          ))}
        </div>
        <div className="session-categories__description">
          <p className="session-categories__text">{description}</p>
        </div>
      </section>
    </div>
  );
}
