/**
 * DAM Gallery Block - Edit Component
 */

import { __ } from '@wordpress/i18n';
import { useBlockProps, BlockControls, InspectorControls } from '@wordpress/block-editor';
import { 
  PanelBody, 
  RangeControl, 
  ToggleControl, 
  SelectControl,
  Button,
  Placeholder,
  ToolbarGroup,
  ToolbarButton
} from '@wordpress/components';
import { useState } from '@wordpress/element';
import ServerSideRender from '@wordpress/server-side-render';

export default function Edit({ attributes, setAttributes }) {
  const {
    assetIds,
    assets,
    columns,
    imageCrop,
    linkTo,
    galleryLayout,
    captionEnabled,
    lightboxEnabled,
    gapSize
  } = attributes;

  const blockProps = useBlockProps();

  // Function to open the DAM asset picker
  const openAssetPicker = () => {
    if (window.damAssetPicker) {
      window.damAssetPicker.open({
        multiple: true,
        mimeTypeFilter: 'image/',
        onSelect: (selectedAssets) => {
          if (selectedAssets && selectedAssets.length > 0) {
            setAttributes({
              assetIds: selectedAssets.map(asset => asset.id),
              assets: selectedAssets,
            });
          }
        }
      });
    } else {
      alert(__('DAM Asset Picker is not available. Please check your plugin configuration.', 'universal-dam'));
    }
  };

  const clearGallery = () => {
    setAttributes({
      assetIds: [],
      assets: [],
    });
  };

  // If no assets selected, show placeholder
  if (!assetIds || assetIds.length === 0) {
    return (
      <div {...blockProps}>
        <Placeholder
          icon="format-gallery"
          label={__('DAM Gallery', 'universal-dam')}
          instructions={__('Select images from your Digital Asset Management system to create a gallery', 'universal-dam')}
        >
          <Button
            variant="primary"
            onClick={openAssetPicker}
          >
            {__('Select DAM Assets', 'universal-dam')}
          </Button>
        </Placeholder>
      </div>
    );
  }

  return (
    <>
      <BlockControls>
        <ToolbarGroup>
          <ToolbarButton
            icon="plus"
            label={__('Add Images', 'universal-dam')}
            onClick={openAssetPicker}
          />
          <ToolbarButton
            icon="trash"
            label={__('Clear Gallery', 'universal-dam')}
            onClick={clearGallery}
          />
        </ToolbarGroup>
      </BlockControls>

      <InspectorControls>
        <PanelBody title={__('Gallery Settings', 'universal-dam')} initialOpen={true}>
          <SelectControl
            label={__('Layout', 'universal-dam')}
            value={galleryLayout}
            options={[
              { label: __('Grid', 'universal-dam'), value: 'grid' },
              { label: __('Masonry', 'universal-dam'), value: 'masonry' },
              { label: __('Carousel', 'universal-dam'), value: 'carousel' },
            ]}
            onChange={(value) => setAttributes({ galleryLayout: value })}
          />

          <RangeControl
            label={__('Columns', 'universal-dam')}
            value={columns}
            onChange={(value) => setAttributes({ columns: value })}
            min={1}
            max={6}
            help={__('Number of columns in the gallery grid', 'universal-dam')}
          />

          <RangeControl
            label={__('Gap Size', 'universal-dam')}
            value={gapSize}
            onChange={(value) => setAttributes({ gapSize: value })}
            min={0}
            max={50}
            help={__('Space between gallery items (in pixels)', 'universal-dam')}
          />

          <ToggleControl
            label={__('Crop Images', 'universal-dam')}
            checked={imageCrop}
            onChange={(value) => setAttributes({ imageCrop: value })}
            help={__('Crop images to fit uniformly in the gallery', 'universal-dam')}
          />

          <ToggleControl
            label={__('Show Captions', 'universal-dam')}
            checked={captionEnabled}
            onChange={(value) => setAttributes({ captionEnabled: value })}
            help={__('Display image captions from DAM metadata', 'universal-dam')}
          />

          <ToggleControl
            label={__('Enable Lightbox', 'universal-dam')}
            checked={lightboxEnabled}
            onChange={(value) => setAttributes({ lightboxEnabled: value })}
            help={__('Open images in a lightbox when clicked', 'universal-dam')}
          />
        </PanelBody>

        <PanelBody title={__('Link Settings', 'universal-dam')} initialOpen={false}>
          <SelectControl
            label={__('Link To', 'universal-dam')}
            value={linkTo}
            options={[
              { label: __('None', 'universal-dam'), value: 'none' },
              { label: __('Media File', 'universal-dam'), value: 'media' },
              { label: __('Attachment Page', 'universal-dam'), value: 'attachment' },
            ]}
            onChange={(value) => setAttributes({ linkTo: value })}
            help={__('Where gallery images should link to', 'universal-dam')}
          />
        </PanelBody>

        <PanelBody title={__('Gallery Info', 'universal-dam')} initialOpen={false}>
          <p>
            <strong>{__('Images:', 'universal-dam')}</strong> {assetIds.length}
          </p>
        </PanelBody>
      </InspectorControls>

      <div {...blockProps}>
        <ServerSideRender
          block="dam/gallery"
          attributes={attributes}
        />
      </div>
    </>
  );
}
