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

export const FileDesignEdit = (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 ?? {};

  // Matches Divi 4 FileDesign: url (any file) + align
  const url   = moduleData.url   ?? '';
  const align = moduleData.align ?? 'left';

  useEffect(() => {
    if (!url) return;

    const shortcode = `[wpmffiledesign url="${url}" align="${align}"]`;

    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(); };
  }, [url, align]);

  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">
        {!url ? (
          <div style={{ backgroundColor: '#f0f0f0', padding: '20px', textAlign: 'center', border: '2px dashed #ccc' }}>
            <strong>WPMF Media Download</strong>
            <p style={{ margin: '8px 0 0', fontSize: '13px', color: '#666' }}>
              Select a media file and transform it into a download button.
            </p>
          </div>
        ) : !isLoading && response?.html ? (
          <div dangerouslySetInnerHTML={{ __html: response.html }} />
        ) : (
          <div style={{ backgroundColor: '#fafafa', padding: '20px', textAlign: 'center', border: '1px solid #ccc' }}>
            <strong>WPMF Media Download Loading...</strong>
          </div>
        )}
      </div>
    </ModuleContainer>
  );
};
