import React, { useLayoutEffect, useMemo, useRef, useState } from 'react';
import PropTypes from 'prop-types';
import CapRow from '@capillarytech/cap-ui-library/CapRow';
import CapLabel from '@capillarytech/cap-ui-library/CapLabel';
import CapImage from '@capillarytech/cap-ui-library/CapImage';

const getTrimmedText = (value = '') => (value ?? '').trim();
const hasTrimmedText = (value = '') => Boolean(getTrimmedText(value));

const getCarouselButtonsWithTitles = (card) => (
  (card?.buttons ?? []).filter((button) => hasTrimmedText(button?.title)).slice(0, 2)
);

const getCarouselButtonSlotCount = (cards = []) => {
  const buttonCounts = cards.map((card) => getCarouselButtonsWithTitles(card).length);
  return Math.min(2, Math.max(0, ...buttonCounts, 0));
};

const ViberCarouselPreviewCards = ({ cards = [] }) => {
  const previewCards = Array.isArray(cards) && cards.length ? cards : [{}];
  const carouselButtonSlotCount = useMemo(
    () => getCarouselButtonSlotCount(previewCards),
    [previewCards],
  );
  const carouselTitleRefs = useRef([]);
  const [carouselTitleLineCount, setCarouselTitleLineCount] = useState(1);

  carouselTitleRefs.current = previewCards.map(() => null);

  useLayoutEffect(() => {
    let maxLines = 1;
    carouselTitleRefs.current.forEach((node) => {
      if (!node) {
        return;
      }
      const { lineHeight } = window.getComputedStyle(node);
      const parsedLineHeight = parseFloat(lineHeight) || 18;
      const lines = Math.min(2, Math.max(1, Math.round(node.scrollHeight / parsedLineHeight)));
      if (lines > maxLines) {
        maxLines = lines;
      }
    });
    setCarouselTitleLineCount((prev) => (prev === maxLines ? prev : maxLines));
  }, [previewCards]);

  return (
    <CapRow className="viber-carousel-preview-scroll">
      {previewCards.map((card, index) => {
        const cardButtons = getCarouselButtonsWithTitles(card);
        const titleLineClass = `viber-carousel-preview-text-wrap--${carouselTitleLineCount}-line`;

        return (
          <CapRow className="viber-carousel-preview-card" key={`viber-carousel-preview-card-${index}`}>
            {hasTrimmedText(card?.mediaUrl) ? (
              <CapImage
                src={card?.mediaUrl}
                className="viber-carousel-preview-image"
                alt="Viber carousel card"
              />
            ) : (
              <CapRow className="viber-carousel-preview-image-placeholder" />
            )}
            <CapRow className="viber-carousel-preview-card-body">
              <CapRow className={`viber-carousel-preview-text-wrap ${titleLineClass}`}>
                {hasTrimmedText(card?.text) ? (
                  <div
                    className="viber-carousel-preview-text-inner"
                    ref={(node) => {
                      carouselTitleRefs.current[index] = node;
                    }}
                  >
                    <CapLabel type="label15" className="viber-carousel-preview-text">
                      {card?.text}
                    </CapLabel>
                  </div>
                ) : (
                  <CapLabel type="label15" className="viber-carousel-preview-text-placeholder" />
                )}
              </CapRow>
              {carouselButtonSlotCount > 0 && (
                <CapRow className="viber-carousel-preview-buttons">
                  {Array.from({ length: carouselButtonSlotCount }).map((_, btnIndex) => {
                    const cardButton = cardButtons[btnIndex];
                    const trimmedCardButtonTitle = cardButton
                      ? getTrimmedText(cardButton?.title)
                      : '';

                    if (!trimmedCardButtonTitle) {
                      return (
                        <CapRow
                          className="viber-carousel-preview-button viber-carousel-preview-button-placeholder"
                          key={`viber-carousel-preview-btn-placeholder-${index}-${btnIndex}`}
                          aria-hidden="true"
                        />
                      );
                    }

                    return (
                      <CapLabel
                        className={`viber-carousel-preview-button ${btnIndex === 1 ? 'viber-carousel-preview-button-secondary' : ''}`}
                        key={`viber-carousel-preview-btn-${index}-${btnIndex}-${trimmedCardButtonTitle}`}
                      >
                        {trimmedCardButtonTitle}
                      </CapLabel>
                    );
                  })}
                </CapRow>
              )}
            </CapRow>
          </CapRow>
        );
      })}
    </CapRow>
  );
};

ViberCarouselPreviewCards.propTypes = {
  cards: PropTypes.arrayOf(PropTypes.shape({
    text: PropTypes.string,
    mediaUrl: PropTypes.string,
    buttons: PropTypes.arrayOf(PropTypes.shape({
      title: PropTypes.string,
      action: PropTypes.string,
    })),
  })),
};

ViberCarouselPreviewCards.defaultProps = {
  cards: [],
};

export default ViberCarouselPreviewCards;
