import { Tabs } from 'antd';
import Divider from 'client/Elements/Divider';
import { SecondaryColoredText } from 'client/Elements/Text';
import colors from 'client/UIKit/colors';
import { Box, Flex } from 'client/UIKit/grid';
import mq from 'client/UIKit/mq';
import styled from 'styled-components';
import elementsRenderProps from '../Elements/props/render';
import elementsTitles from '../Elements/titles';
import { buildElement } from '../lib/buildElement';

const ElementTitle = styled.h5`
  color: rgba(0, 0, 0, 0.75);
  font-weight: 600;
  font-size: 14px;
  line-height: 1.5;
  margin: 0 8px 3px 0;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
`;

const renderElements = ({ elements }) => {
  return elements.map(elementName => {
    const elementTitleText = elementsTitles[elementName];
    const Title = () => <ElementTitle>{elementTitleText}</ElementTitle>;
    const Element = buildElement(elementName);

    if (elementsRenderProps[elementName]) {
      const { render } = elementsRenderProps[elementName];
      return render(Title, Element);
    }

    return (
      <Flex flexDirection="column" key={elementName}>
        <Title />
        <Element />
      </Flex>
    );
  });
};

const ElementsGrid = styled(Box)`
  display: grid;
  grid-gap: 10px;

  grid-template-columns: 1fr;
  ${mq.laptop`
      grid-template-columns:${props =>
        props.gridTemplateColumns ||
        `repeat(${props.columnsNumber || props.defaultColumnsNumber},1fr)`}
  `}
`;

const renderBlocks = ({ blocks }) => {
  return blocks?.map((block, ib) => {
    const { elements, title, style } = block;
    return (
      <Flex key={ib} flexDirection="column" flexWrap="nowrap">
        {title && <SecondaryColoredText>{title}</SecondaryColoredText>}
        <ElementsGrid {...style} defaultColumnsNumber={1}>
          {renderElements({ elements })}
        </ElementsGrid>
      </Flex>
    );
  });
};

const BlocksTitle = styled(Divider)`
  margin: 16px 0;
  color: ${colors.primary} !important;
  font-size: 0.95rem;
`;

export const renderGroups = ({ groups }) => {
  return groups?.map((group, ig) => {
    const { title, blocks, style } = group;

    return (
      <Box key={ig} my="5px">
        {title && <BlocksTitle>{title}</BlocksTitle>}
        <ElementsGrid {...style} defaultColumnsNumber={2}>
          {renderBlocks({ blocks })}
        </ElementsGrid>
      </Box>
    );
  });
};

export const renderSections = ({ sectionsList }) => {
  return (
    <Tabs type="line" tabBarGutter="22px">
      {sectionsList.map((section, is) => {
        const { title, groups } = section;
        return (
          <Tabs.TabPane tab={title} key={is} forceRender>
            {renderGroups({ groups })}
          </Tabs.TabPane>
        );
      })}
    </Tabs>
  );
};
