import React, { FC, ReactNode, useEffect, useRef, useState } from 'react';

import css from './index.module.css';
import classNames from 'classnames';
import SaleSVG from '../../assets/icons/ribbon-sale.svg';

export interface RowsProps {
  children?: ReactNode;
  variant?:
    | 'default'
    | 'bubble'
    | 'table'
    | 'roles'
    | 'cards'
    | 'cards-small'
    | 'partners'
    | 'campaign';
  width?: string;
  fullWidthCampaign?: boolean;
}

const Rows: FC<RowsProps> = ({
  children,
  variant = 'default',
  width,
  fullWidthCampaign = false,
}) => {
  const ref = useRef(null);
  const [circleColor, setCircleColor] = useState('#FAFAFA');

  useEffect(() => {
    if (variant === 'bubble') {
      const backgroundColor = window.getComputedStyle(ref.current.parentNode)
        .backgroundColor;

      setCircleColor(
        backgroundColor && backgroundColor === 'rgb(250, 250, 250)'
          ? '#FFFFFF'
          : '#FAFAFA',
      );
    }
  }, [variant]);

  return (
    <div
      ref={ref}
      className={classNames(css.rows, {
        [css.rows__table]: variant === 'table',
        [css.rows__bubble]: variant === 'bubble',
        [css.rows__roles]: variant === 'roles',
        [css.rows__cards]: variant === 'cards',
        [css.rows__cardsSmall]: variant === 'cards-small',
        [css.rows__partners]: variant === 'partners',
        [css.rows__campaign]: variant === 'campaign',
        [css.rows__campaign__packages]:
          variant === 'campaign' && !fullWidthCampaign,
      })}
      style={
        width && variant != 'partners'
          ? { gridTemplateColumns: `repeat(auto-fit, minmax(${width}, 1fr))` }
          : null
      }
      {...{
        count: React.Children.count(children),
      }}
    >
      {React.Children.map(children, child => {
        return variant === 'campaign' && !fullWidthCampaign ? (
          <div className={css.rows__campaign__item}>
            <div className={css.ribbon}>
              <SaleSVG />
            </div>
            {child}
          </div>
        ) : (
          <div className={css.rows__item}>
            {child}
            {variant === 'bubble' && (
              <div
                className={css.rows__itemCircle}
                style={{ backgroundColor: circleColor }}
              />
            )}
          </div>
        );
      })}
    </div>
  );
};

export default Rows;
