import React from 'react';

import { ModuleStyles } from './module-styles';
import { ModuleScriptData } from './module-script-data';
import { moduleClassnames } from './module-classnames';
import { getLoopData } from './dynamic-options';

const { ModuleContainer } = window?.divi?.module ?? {};

const attrValue = (attrs, name, fallback = '') =>
  attrs?.[name]?.innerContent?.desktop?.value ?? fallback;

const LoopPreview = ({ attrs }) => {
  const field = attrValue(attrs, 'loopField', 'empty');
  const showImage = attrValue(attrs, 'loopShowImage', 'on') === 'on';
  const showTitle = attrValue(attrs, 'loopShowTitle', 'on') === 'on';
  const showTerms = attrValue(attrs, 'loopShowTerms', 'off') === 'on';
  const showExcerpt = attrValue(attrs, 'loopShowExcerpt', 'on') === 'on';
  const showLink = attrValue(attrs, 'loopShowLink', 'on') === 'on';
  const linkTxt = attrValue(attrs, 'loopLinkTxt', 'Learn More');
  const linkTarget = attrValue(attrs, 'loopLinkTarget', '_self');
  const cardWidth = attrValue(attrs, 'loopCardWidth', '250');
  const cardHeight = attrValue(attrs, 'loopCardHeight', '250');

  const posts = getLoopData().posts?.[field] ?? [];

  if (!posts.length) {
    return (
      <div className="lknscf-main-container">
        <div className="lknscf-posts-grid">
          <p className="no-images" style={{ width: '100%', textAlign: 'center' }}>
            No posts found for the selected SCF object field.
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="lknscf-main-container">
      <div className="lknscf-posts-grid">
        {posts.map((post, index) => (
          <article
            key={post.id ?? index}
            className={`lknscf-post ${(post.classes ?? []).join(' ')}`}
            data-url={post.permalink}
            style={{ width: `${cardWidth}px`, height: `${cardHeight}px` }}
          >
            {showImage && post.img_html && (showLink ? (
              <a className="lknscf-post-link" href={post.permalink} target={linkTarget}>
                {/* eslint-disable-next-line react/no-danger */}
                <figure className="lknscf-post-figure" dangerouslySetInnerHTML={{ __html: post.img_html }} />
              </a>
            ) : (
              <figure className="lknscf-post-figure" dangerouslySetInnerHTML={{ __html: post.img_html }} />
            ))}
            {showTitle && (
              <h3 className="lknscf-post-title" dangerouslySetInnerHTML={{ __html: post.title }} />
            )}
            {showTerms && post.terms && (
              <div className="lknscf-post-terms" dangerouslySetInnerHTML={{ __html: post.terms }} />
            )}
            {showExcerpt && post.excerpt && (
              <div className="lknscf-post-excerpt" dangerouslySetInnerHTML={{ __html: post.excerpt }} />
            )}
            {showLink && (
              <div className="lknscf-post-link-container">
                <div className="lknscf-link">
                  <a className="lknscf-post-link" href={post.permalink} target={linkTarget}>
                    {linkTxt}
                  </a>
                </div>
              </div>
            )}
          </article>
        ))}
      </div>
    </div>
  );
};

export const LoopEdit = ({ attrs, elements, id, name }) => (
  <ModuleContainer
    attrs={attrs}
    elements={elements}
    id={id}
    name={name}
    scriptDataComponent={ModuleScriptData}
    stylesComponent={ModuleStyles}
    classnamesFunction={moduleClassnames}
  >
    {elements.styleComponents({ attrName: 'module' })}
    <div className="et_pb_module_inner">
      <LoopPreview attrs={attrs} />
    </div>
  </ModuleContainer>
);
