import React from 'react';
import {PrimaryButtonDarkLink} from 'src/components';
import {ImageTextGridType} from 'src/interfaces';
import {ComponentWrapper} from '../../layouts/wrappers';
import {
  ImageTextGridContainer,
  Title,
  BlocksContainer,
  BlockItem,
  BlockCopyContainer,
  BlockSubtitle,
  BlockSubtext,
  BlockImage,
  BlockButtonWrapper,
} from './imageTextCards.styles';

export const IMAGE_TEXT_GRID_NAME = 'Page_Sections_layout_Content_ImageTextGrid';

export const IMAGE_TEXT_GRID_QUERY = `
  ${IMAGE_TEXT_GRID_NAME} {
    fieldGroupName
    titleEn
    titleSp
    blocks {
      buttonLink
      buttonLinkSp
      buttonTextEn
      buttonTextSp
      subtextSp
      subtitleEn
      subtitleSp
      subtextEn
      image {
        altText
        sourceUrl
      }
    }
  }
`;

interface ImageTextGridProps {
  titleEn: string;
  titleSp: string;
  blocks: ImageTextGridType[];
  language: string;
}

export const ImageTextGrid: React.FC<ImageTextGridProps> = ({titleEn, titleSp, language, blocks}): JSX.Element => {
  const title = language === 'english' ? titleEn : titleSp;

  blocks = blocks.map(block => {
    return language === 'english'
      ? {
          subtitle: block.subtitleEn as string,
          subtext: block.subtextEn as string,
          buttonText: block.buttonTextEn as string,
          buttonLink: block.buttonLink,
          image: block.image,
        }
      : {
          subtitle: block.subtitleSp as string,
          subtext: block.subtextSp as string,
          buttonText: block.buttonTextSp as string,
          buttonLink: block.buttonLinkSp,
          image: block.image,
        };
  });

  return (
    <ComponentWrapper>
      <ImageTextGridContainer>
        {title != "" && <Title>{title}</Title>}
        <BlocksContainer>
          {blocks.map(({subtitle, subtext, buttonText, buttonLink, image}, idx) => (
            <BlockItem key={`${subtitle} - ${idx}`}>
              {image && <BlockImage src={image.sourceUrl} alt={image.altText} />}
              <BlockCopyContainer>
                {subtitle != "" && <BlockSubtitle>{subtitle}</BlockSubtitle>}
                {subtext != "" && <BlockSubtext dangerouslySetInnerHTML={{__html: subtext}}></BlockSubtext>}
                {buttonLink && (
                  <BlockButtonWrapper>
                    <PrimaryButtonDarkLink href={buttonLink}>{buttonText}</PrimaryButtonDarkLink>
                  </BlockButtonWrapper>
                )}
              </BlockCopyContainer>
            </BlockItem>
          ))}
        </BlocksContainer>
      </ImageTextGridContainer>
    </ComponentWrapper>
  );
};

export default ImageTextGrid;
