/**
 * DAM Image Block - Edit Component
 */

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

export default function Edit({ attributes, setAttributes }) {
  const {
    assetId,
    assetUrl,
    assetData,
    alt,
    caption,
    width,
    height,
    sizeSlug,
    focalPoint,
    linkDestination,
    linkUrl,
    linkTarget,
    alignment
  } = attributes;

  const [showPicker, setShowPicker] = useState(false);

  const blockProps = useBlockProps({
    className: `align${alignment}`
  });

  // Function to open the DAM asset picker
  const openAssetPicker = () => {
    // This will trigger the Svelte AssetPicker component
    if (window.damAssetPicker) {
      window.damAssetPicker.open({
        multiple: false,
        mimeTypeFilter: 'image/',
        onSelect: (assets) => {
          if (assets && assets.length > 0) {
            const asset = assets[0];
            setAttributes({
              assetId: asset.id,
              assetUrl: asset.url,
              assetData: asset,
              alt: asset.metadata?.alt || asset.metadata?.title || '',
            });
          }
        }
      });
    } else {
      alert(__('DAM Asset Picker is not available. Please check your plugin configuration.', 'universal-dam'));
    }
  };

  const removeAsset = () => {
    setAttributes({
      assetId: '',
      assetUrl: '',
      assetData: {},
      alt: '',
    });
  };

  const imageSizes = [
    { label: __('Thumbnail', 'universal-dam'), value: 'thumbnail' },
    { label: __('Medium', 'universal-dam'), value: 'medium' },
    { label: __('Large', 'universal-dam'), value: 'large' },
    { label: __('Full Size', 'universal-dam'), value: 'full' },
  ];

  // If no asset selected, show placeholder
  if (!assetId) {
    return (
      <div {...blockProps}>
        <Placeholder
          icon="format-image"
          label={__('DAM Image', 'universal-dam')}
          instructions={__('Select an image from your Digital Asset Management system', 'universal-dam')}
        >
          <Button
            variant="primary"
            onClick={openAssetPicker}
          >
            {__('Select DAM Asset', 'universal-dam')}
          </Button>
        </Placeholder>
      </div>
    );
  }

  return (
    <>
      <BlockControls>
        <ToolbarGroup>
          <ToolbarButton
            icon="edit"
            label={__('Replace Image', 'universal-dam')}
            onClick={openAssetPicker}
          />
          <ToolbarButton
            icon="trash"
            label={__('Remove Image', 'universal-dam')}
            onClick={removeAsset}
          />
        </ToolbarGroup>
      </BlockControls>

      <InspectorControls>
        <PanelBody title={__('Image Settings', 'universal-dam')} initialOpen={true}>
          <TextControl
            label={__('Alt Text', 'universal-dam')}
            value={alt}
            onChange={(value) => setAttributes({ alt: value })}
            help={__('Describe the image for screen readers and SEO', 'universal-dam')}
          />

          <SelectControl
            label={__('Image Size', 'universal-dam')}
            value={sizeSlug}
            options={imageSizes}
            onChange={(value) => setAttributes({ sizeSlug: value })}
          />

          <RangeControl
            label={__('Width', 'universal-dam')}
            value={width || assetData.width || 0}
            onChange={(value) => setAttributes({ width: value })}
            min={0}
            max={2000}
          />

          <RangeControl
            label={__('Height', 'universal-dam')}
            value={height || assetData.height || 0}
            onChange={(value) => setAttributes({ height: value })}
            min={0}
            max={2000}
          />
        </PanelBody>

        <PanelBody title={__('Focal Point', 'universal-dam')} initialOpen={false}>
          {assetUrl && (
            <FocalPointPicker
              url={assetUrl}
              value={focalPoint}
              onChange={(value) => setAttributes({ focalPoint: value })}
            />
          )}
        </PanelBody>

        <PanelBody title={__('Link Settings', 'universal-dam')} initialOpen={false}>
          <SelectControl
            label={__('Link To', 'universal-dam')}
            value={linkDestination}
            options={[
              { label: __('None', 'universal-dam'), value: 'none' },
              { label: __('Media File', 'universal-dam'), value: 'media' },
              { label: __('Custom URL', 'universal-dam'), value: 'custom' },
            ]}
            onChange={(value) => setAttributes({ linkDestination: value })}
          />

          {linkDestination === 'custom' && (
            <>
              <TextControl
                label={__('URL', 'universal-dam')}
                value={linkUrl}
                onChange={(value) => setAttributes({ linkUrl: value })}
                type="url"
              />

              <SelectControl
                label={__('Link Target', 'universal-dam')}
                value={linkTarget}
                options={[
                  { label: __('Same Window', 'universal-dam'), value: '_self' },
                  { label: __('New Window', 'universal-dam'), value: '_blank' },
                ]}
                onChange={(value) => setAttributes({ linkTarget: value })}
              />
            </>
          )}
        </PanelBody>
      </InspectorControls>

      <figure {...blockProps}>
        <ServerSideRender
          block="dam/image"
          attributes={attributes}
        />
        {caption && (
          <RichText
            tagName="figcaption"
            value={caption}
            onChange={(value) => setAttributes({ caption: value })}
            placeholder={__('Add caption...', 'universal-dam')}
          />
        )}
      </figure>
    </>
  );
}
