/* eslint-disable */

import React, { FC, ReactType, ReactNode, useState, useRef } from 'react';
import classnames from 'classnames';
import Layout from '../../components/Layout';
import Button from '../../blocks/Button';
import Price from '../../blocks/Price';
import css from './index.module.css';
import Accordion from '../../blocks/Accordion';
import Banner, { BannerProps } from '../../components/Banner';
import SVGStarFilled from '../../assets/icons/icon-star-filled.svg';
import SVGStarStroked from '../../assets/icons/icon-star-stroked.svg';
import SVGStarStrokedHalf from '../../assets/icons/icon-star-stroked-half.svg';
import ClockSVG from '../../assets/icons/clock.svg';

import { useScrollPosition } from '@n8tb1t/use-scroll-position';
import Discount from '../../blocks/Discount';
import { getAmountWithCurrency, getReduction } from '../../helpers/priceHelper';
import Ribbon from '../../components/Ribbon';
import SaleSVG from '../../assets/icons/ribbon-sale.svg';

export interface PackagePageProps {
  id: number;
  name: string;
  title: string;
  titleDescription: string;
  description: string;
  descriptionMore?: string;
  Image?: ReactType;
  ImageProps: unknown;
  price: number;
  originalPrice?: number;
  priceLabelMessage: string;
  currencyIsoCode: string;
  Link: ReactType;
  ButtonToCheckout: ReactType;
  BannerProps?: BannerProps;
  duration?: string;
  durationType?: string;
  durationTypeText?: string;
  durationLabel?: string;
  faq?: ReactType;
  averageRating: number;
  rating?: number;
  ratings?: {
    count: number;
    items: {
      id: number;
      firstName: string;
      rating: number;
      feedback: string;
      createdAt: string;
    }[];
  };
  faqs?: {
    id: number;
    question: string;
    answer: string;
  }[];
  reviews?: ReactType;
  selectedOption?: string;
  partnerType?: string;
  partnerMessage: string;
  partnerMessageDescription: string;
  showMoreRatingsLabel: string;
  handleRatingShowMoreClick?: () => void;
  isLoadingRatings?: boolean;
  ratingsLabel: string;
  notes?: string;
  notesTitle: string;
  campaign?: string;
}

export interface ContentProps {
  background?: {
    grey?: boolean;
  };
  small?: boolean;
  noPadding?: boolean;
  noPaddingBottom?: boolean;
  noPaddingTop?: boolean;
  isFullWidthOnLarge?: boolean;
  children?: ReactNode;
}

const ContentPackage: FC<ContentProps> = ({
  children,
  small = false,
  background = { grey: false },
  noPadding = false,
  noPaddingBottom = false,
  noPaddingTop = false,
  isFullWidthOnLarge = false,
}) => {
  return (
    <div
      className={classnames({
        [css.content]: true,
        [css.contentSmall]: small,
        [css.contentGrey]: background.grey,
        [css.contentNoPadding]: noPadding,
        [css.contentNoPaddingBottom]: noPaddingBottom,
        [css.contentNoPaddingTop]: noPaddingTop,
      })}
    >
      <div
        className={classnames({
          [css.content__wrap]: !isFullWidthOnLarge,
          [css.content__wrapFull]: isFullWidthOnLarge,
        })}
      >
        {children}
      </div>
    </div>
  );
};

const PackageTemplate: FC<PackagePageProps> = ({
  id,
  title,
  Image,
  ImageProps,
  titleDescription,
  description,
  notesTitle,
  notes,
  descriptionMore,
  price,
  originalPrice,
  priceLabelMessage,
  currencyIsoCode,
  ButtonToCheckout,
  duration,
  durationType,
  durationTypeText,
  durationLabel,
  faq,
  averageRating,
  rating,
  ratings,
  reviews,
  faqs,
  selectedOption, // TODO set by selectoin or a default
  partnerType,
  partnerMessage,
  partnerMessageDescription,
  name,
  handleRatingShowMoreClick,
  showMoreRatingsLabel,
  isLoadingRatings,
  ratingsLabel,
  campaign,
}) => {
  const [showElement, setShowElement] = useState(false);
  const elementRef = useRef();

  const roundToPrecision = (x, precision) => {
    var y = +x + (precision === undefined ? 0.5 : precision / 2);
    return y - (y % (precision === undefined ? 1 : +precision));
  };

  // Element scroll position
  useScrollPosition(
    ({ currPos }) => {
      if (currPos.y < 0) {
        setShowElement(true);
      } else {
        setShowElement(false);
      }
    },
    [],
    elementRef,
  );

  const ratingPrecise = roundToPrecision(averageRating, 0.5);
  const fullStars =
    ratingPrecise % 2 === 1 ? ratingPrecise : Math.floor(ratingPrecise);
  const halfStars = ratingPrecise % 2 === 1 ? 0 : 1;
  const strokedStars = 5 - fullStars - halfStars;
  return (
    <Layout>
      <div className={css.packagePage}>
        <div className={css.packagePage__banner}>
          {campaign ? (
            <Banner
              isPackage={true}
              bannerBackgroundColor={
                'linear-gradient(90deg, rgba(29,29,29,1) 0%, rgba(68,68,68,1) 100%)'
              }
            />
          ) : (
            <Banner Image={Image} ImageProps={ImageProps} isPackage={true} />
          )}
        </div>
        <div className={css.packagePage__content}>
          <div className={css.packagePage__contentWrap}>
            <div
              className={classnames([
                css.packagePage__contentStep,
                css.packagePage__contentStep1,
              ])}
            >
              <ContentPackage>
                {campaign && (
                  <div className={css.packagePage__saleRibbon}>
                    <SaleSVG />
                  </div>
                )}
                <h1
                  data-test-id="title-main"
                  className={classnames({
                    [css.packagePage__title]: true,
                    [css.packagePage__titleCampaign]: campaign,
                  })}
                >
                  {title}
                </h1>
                {originalPrice && (
                  <div
                    className={classnames([
                      css.packagePage__priceWrap,
                      css.packagePage__discount,
                    ])}
                  >
                    <Discount
                      reduction={getReduction(
                        originalPrice,
                        price,
                        currencyIsoCode,
                      )}
                    />
                  </div>
                )}
                {price && (
                  <div className={css.packagePage__priceWrap}>
                    <div
                      className={classnames({
                        [css.packagePage__price]: true,
                        [css.packagePage__priceDiscounted]:
                          campaign && originalPrice,
                      })}
                    >
                      <div
                        className={classnames([
                          css.packagePage__priceCol,
                          css.packagePage__priceLabel,
                        ])}
                      >
                        <Price
                          original={
                            originalPrice &&
                            getAmountWithCurrency(
                              originalPrice,
                              currencyIsoCode,
                              partnerType,
                            )
                          }
                          amount={getAmountWithCurrency(
                            price,
                            currencyIsoCode,
                            partnerType,
                          )}
                        />{' '}
                        <span className={css.packagePage__duration}>
                          {' '}
                          {' / '}
                          {duration}{' '}
                          {durationType === 'Minutes' ? 'Min.' : 'N/D'}
                        </span>
                      </div>
                    </div>
                  </div>
                )}
                <div ref={elementRef}>
                  <div className={css.packagePage__cta}>
                    {ButtonToCheckout && <ButtonToCheckout />}
                  </div>
                </div>
                {ratings && ratings.count > 0 && (
                  <div className={css.packagePage__ratingAverage}>
                    <div className={css.packagePage__ratingAverageStars}>
                      {fullStars > 0 &&
                        [...Array(fullStars).keys()].map((rating, idx) => (
                          <SVGStarFilled
                            key={`rating-average-'${rating}-${idx}`}
                            width={15}
                          />
                        ))}

                      {halfStars > 0 &&
                        [...Array(halfStars).keys()].map((rating, idx) => (
                          <SVGStarStrokedHalf
                            key={`rating-average-stroked-half-star`}
                            width={15}
                          />
                        ))}

                      {strokedStars > 0 &&
                        [...Array(strokedStars).keys()].map((rating, idx) => (
                          <SVGStarStroked
                            key={`rating-average-stroked-star`}
                            width={15}
                          />
                        ))}
                      <a href="#ratings">
                        {ratings && ratings.count} {ratingsLabel}
                      </a>
                    </div>
                  </div>
                )}
                {partnerType.toLowerCase() === 'friend' && (
                  <div className={css.packagePage__priceInfo}>
                    * {priceLabelMessage}
                  </div>
                )}
              </ContentPackage>
            </div>
            <div
              className={classnames([
                css.packagePage__contentStep,
                css.packagePage__contentStep2,
              ])}
            >
              <ContentPackage small>
                <div>
                  {description && <p key={description}>{description}</p>}
                </div>
                <br />
                {descriptionMore && (
                  <>
                    <h2 className={css.packagePage__sectionTitle}>
                      {titleDescription}
                    </h2>
                    <ul className={css.packagePage__descriptionList}>
                      {duration && (
                        <li>
                          {durationLabel}: {duration} {durationTypeText}
                        </li>
                      )}
                      <li>{partnerMessage}**</li>
                      {descriptionMore &&
                        descriptionMore
                          .split('\n')
                          .map(line => <li key={line}>{line}</li>)}
                    </ul>
                  </>
                )}
                {notes && (
                  <div className={css.packagePage__notesBox}>
                    <h2 className={css.packagePage__sectionTitle}>
                      {notesTitle}
                    </h2>
                    {notes}
                  </div>
                )}
                <div
                  className={css.packagePage__partnerMessageFriendDescription}
                >
                  **{partnerMessageDescription}
                </div>
              </ContentPackage>
            </div>
            {ratings && ratings.count > 0 && (
              <div
                className={classnames([
                  css.packagePage__contentStep,
                  css.packagePage__contentStep3,
                ])}
              >
                <ContentPackage small>
                  <h2 id="ratings" className={css.packagePage__sectionTitle}>
                    {ratingsLabel}
                  </h2>
                  <div className={css.packagePage__ratingWrap}>
                    {ratings.items.map((rating, idx) => (
                      <div
                        key={`${rating.toString()}${idx}`}
                        className={css.packagePage__ratingCard}
                      >
                        <div className={css.packagePage__ratingCardStars}>
                          {[...Array(Math.floor(rating.rating))].map(
                            (rating, idx) => {
                              return (
                                <SVGStarFilled
                                  key={`rating-'${rating}-${idx}`}
                                  width={15}
                                />
                              );
                            },
                          )}
                          {[...Array(Math.floor(5 - rating.rating))].map(
                            (rating, idx) => {
                              return (
                                <SVGStarStroked
                                  key={`rating-stroked-'${rating}-${idx}`}
                                  width={15}
                                />
                              );
                            },
                          )}
                        </div>
                        <div className={css.packagePage__ratingCardName}>
                          {rating.firstName}{' '}
                          {new Date(rating.createdAt).toLocaleDateString(
                            'de-CH',
                          )}
                        </div>
                        <div className={css.packagePage__ratingCardComment}>
                          {rating.feedback}
                        </div>
                      </div>
                    ))}
                  </div>
                  {!(ratings.count === ratings.items.length) && (
                    <div className={css.packagePage__ratingButtonReadMore}>
                      <Button
                        showThrobber={isLoadingRatings}
                        disabled={isLoadingRatings}
                        variant="tertiary"
                        size="small"
                        handleClick={handleRatingShowMoreClick}
                      >
                        {showMoreRatingsLabel}
                      </Button>
                    </div>
                  )}
                </ContentPackage>
              </div>
            )}
            {faqs && (
              <div
                className={classnames([
                  css.packagePage__contentStep,
                  css.packagePage__contentStep4,
                  css.packagePage__contentStepLast,
                ])}
              >
                <ContentPackage small>
                  <h2 id="faqs" className={css.packagePage__sectionTitle}>
                    FAQ
                  </h2>

                  <div className={css.packagePage__sectionFaqWrap}>
                    {faqs.map(faq => (
                      <Accordion key={faq.id} title={faq.question}>
                        <p>{faq.answer}</p>
                      </Accordion>
                    ))}
                  </div>
                </ContentPackage>
              </div>
            )}

            <div
              className={classnames(css.packagePage__priceStickyHidden, {
                [`${css.packagePage__priceStickyHiddenShow}`]: showElement,
              })}
            >
              <div className={classnames(css.packagePage__sectionPriceSticky)}>
                <div className={css.packagePage__priceSticky}>
                  <ContentPackage small>
                    <div className={css.packagePage__priceStickyWrap}>
                      <div className={css.packagePage__priceStickyDescription}>
                        <div
                          className={classnames([
                            css.packagePage__priceStickyCol,
                            css.packagePage__priceStickyLabel,
                          ])}
                        >
                          {name}
                        </div>
                        <div
                          className={classnames([
                            css.packagePage__priceStickyCol,
                            css.packagePage__priceStickyPrice,
                          ])}
                        >
                          <Price
                            amount={getAmountWithCurrency(
                              price,
                              currencyIsoCode,
                              partnerType,
                            )}
                          />
                        </div>
                      </div>
                      <div className={css.packagePage__priceStickyCta}>
                        {ButtonToCheckout && <ButtonToCheckout />}
                      </div>
                    </div>
                  </ContentPackage>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </Layout>
  );
};

export default PackageTemplate;
