import React, { ReactElement, useEffect, useRef, useState } from 'react';
import { ModuleContainer, StyleContainer } from '@divi/module';
import { useFetch } from '@divi/rest';

export const GalleryEdit = (props: any): ReactElement => {
  const { attrs, id, name, elements } = props;

  const { fetch, response, isLoading } = useFetch<any>(null);
  const fetchAbortRef = useRef<AbortController>();
  const lastShortcodeRef = useRef<string>('');

  const moduleData = attrs?.module?.innerContent?.desktop?.value ?? {};

  const theme          = moduleData.theme          ?? 'default';
  const columns        = moduleData.columns        ?? '3';
  const size           = moduleData.size           ?? 'medium';
  const targetsize     = moduleData.targetsize     ?? 'large';
  const orderby        = moduleData.orderby        ?? 'post__in';
  const order          = moduleData.order          ?? 'ASC';
  const action         = moduleData.action         ?? 'file';
  const gutterwidth    = moduleData.gutterwidth    ?? '5';
  const borderRadius   = moduleData.borderRadius   ?? '0';
  const borderStyle    = moduleData.borderStyle    ?? 'solid';
  const borderWidth    = moduleData.borderWidth    ?? '0';
  const borderColor    = moduleData.borderColor    ?? '#cccccc';
  const galleryFolders = moduleData.galleryFolders ?? 'off';
  const galleryFolderId = moduleData.galleryFolderId ?? '0';
  const aspectRatio    = moduleData.aspectRatio    ?? '1_1';
  // Image IDs from divi/upload-gallery (images attribute), with legacy fallback.
  const items = (attrs?.images?.advanced?.galleryIds?.desktop?.value ?? '').trim()
    || (moduleData.items ?? '');

  useEffect(() => {
    if (items === '' && (galleryFolderId === '0' || galleryFolderId === 0)) {
      return;
    }

    const galleryFoldersInt = galleryFolders === 'on' ? '1' : '0';

    const shortcode = `[wpmf_gallery is_divi="1"`
      + ` include="${items}"`
      + ` display="${theme}"`
      + ` columns="${columns}"`
      + ` size="${size}"`
      + ` targetsize="${targetsize}"`
      + ` link="${action}"`
      + ` wpmf_orderby="${orderby}"`
      + ` wpmf_order="${order}"`
      + ` gutterwidth="${gutterwidth}"`
      + ` img_border_radius="${borderRadius}"`
      + ` border_style="${borderStyle}"`
      + ` border_width="${borderWidth}"`
      + ` border_color="${borderColor}"`
      + ` wpmf_autoinsert="${galleryFoldersInt}"`
      + ` wpmf_folder_id="${galleryFolderId}"`
      + ` aspect_ratio="${aspectRatio}"`
      + `]`;

    if (shortcode === lastShortcodeRef.current) {
      return;
    }
    lastShortcodeRef.current = shortcode;

    if (fetchAbortRef.current) {
      fetchAbortRef.current.abort();
    }
    fetchAbortRef.current = new AbortController();

    fetch({
      restRoute: `/wp/v2/wpmf-block-preview?shortcode=${encodeURIComponent(shortcode)}`,
      method: 'GET',
      signal: fetchAbortRef.current.signal,
    }).catch((error: any) => {
      if (error.name === 'AbortError') return;
      console.error(error);
    });

    return () => {
      if (fetchAbortRef.current) {
        fetchAbortRef.current.abort();
      }
    };
  }, [theme, columns, size, targetsize, orderby, order, action, gutterwidth, borderRadius,
      borderStyle, borderWidth, borderColor, galleryFolders, galleryFolderId, aspectRatio, items]);

  const hasContent = items !== '' || (galleryFolderId !== '0' && galleryFolderId !== 0);

  return (
    <ModuleContainer 
      attrs={attrs} 
      elements={elements} 
      id={id} 
      name={name}
      stylesComponent={(styleProps: any) => (
        <StyleContainer mode={styleProps.mode} state={styleProps.state}>
          {elements.style({ attrName: 'module' })}
        </StyleContainer>
      )}
    >
      {elements.styleComponents({ attrName: 'module' })}
      <div className="wpmf-divi5-module-preview">
        {!hasContent ? (
          <div style={{ backgroundColor: '#f0f0f0', padding: '20px', textAlign: 'center', border: '2px dashed #ccc' }}>
            <strong>WPMF Gallery</strong>
            <p style={{ margin: '8px 0 0', fontSize: '13px', color: '#666' }}>Enter a Folder ID or add images to preview the gallery.</p>
          </div>
        ) : !isLoading && response?.html ? (
          <div dangerouslySetInnerHTML={{ __html: response.html }} />
        ) : (
          <div style={{ backgroundColor: '#fafafa', padding: '20px', textAlign: 'center', border: '1px solid #ccc' }}>
            <strong>WPMF Gallery Preview Loading...</strong>
          </div>
        )}
      </div>
    </ModuleContainer>
  );
};
