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

import { requestJson } from '../../utils';

export const FileEdit = (props: any): ReactElement => {
  const { attrs, id, name, elements } = props;
  const [previewHtml, setPreviewHtml] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const abortRef = useRef<AbortController>();

  const moduleData = attrs?.module?.innerContent?.desktop?.value ?? {};
  const selection = moduleData.selection ?? {};
  const fileId = String(selection.selectedFileId ?? '');
  const categoryId = String(selection.selectedCategoryId ?? '');

  useEffect(() => {
    if (abortRef.current) {
      abortRef.current.abort();
    }

    if (!fileId || !categoryId) {
      setPreviewHtml('');
      setIsLoading(false);
      return;
    }

    abortRef.current = new AbortController();
    setIsLoading(true);

    requestJson(
      {
        action: 'wpfd',
        task: 'file.callFileShortcode',
        file_id: fileId,
        category_id: categoryId,
      },
      abortRef.current.signal
    ).then((response) => {
      setPreviewHtml(response?.data ?? '');
      setIsLoading(false);
    }).catch((error) => {
      if (error?.name !== 'AbortError') {
        setIsLoading(false);
      }
    });

    return () => {
      if (abortRef.current) {
        abortRef.current.abort();
      }
    };
  }, [fileId, categoryId]);

  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' })}
      {!fileId || !categoryId ? (
        <div className="divi-file-container">
          <div id="divi-single-file-placeholder" className="divi-single-file-placeholder">
            <span className="file-message">Please select a WP File Download content to activate the preview</span>
          </div>
        </div>
      ) : isLoading ? (
        <div className="divi-file-container">
          <div className="wpfd-loading-wrapper">
            <strong>Loading file preview...</strong>
          </div>
        </div>
      ) : (
        <div className="divi-file-container">
          <div dangerouslySetInnerHTML={{ __html: previewHtml }} />
        </div>
      )}
    </ModuleContainer>
  );
};
