import React, { useEffect, useRef, useState } from 'react';
import bookingCSS from '../templates/BookingFunnel/index.module.css';
import ArrowSVG from '../assets/icons/icon_angle.svg';
import LogoRawSVG from '../assets/icons/logo-raw.svg';
import Link from '../blocks/Link';
import CloseSVG from '../assets/icons/icon_close.svg';
import AddressMap from '../components/AddressMap';
import { Button } from '../index';
import { getAmountWithCurrency } from './priceHelper';

export const BookingHeader = ({ LinkProps, steps, title }): JSX.Element => {
  const [isSticky, setSticky] = useState(false);
  const headerRef = useRef(null);

  const handleScroll = (): void => {
    if (headerRef.current) {
      setSticky(headerRef.current.getBoundingClientRect().top <= 0);
    }
  };

  useEffect(() => {
    window.addEventListener('scroll', handleScroll);
    return (): void => {
      window.removeEventListener('scroll', () => handleScroll);
    };
  }, []);

  return (
    <>
      <div
        className={
          bookingCSS.booking__header +
          ` ${isSticky ? bookingCSS.booking__headerSticky : ''}`
        }
        ref={headerRef}
      >
        <div className={bookingCSS.booking__headerLogoWrapper}>
          <Link
            {...LinkProps}
            aria-label="Back to home"
            className={bookingCSS.booking__logoLink}
          >
            <span>
              <ArrowSVG className={bookingCSS.booking__headerIcon} />
              back to
            </span>
            <LogoRawSVG className={bookingCSS.booking__headerLogo} />
          </Link>
        </div>
        <div className={bookingCSS.booking__headerPagination}>
          <div className={bookingCSS.booking__headerPaginationInner}>
            <ul>
              <li className={bookingCSS.booking__headerPaginationActive} />
              <li
                className={
                  steps.step2 ? bookingCSS.booking__headerPaginationActive : ''
                }
              />
              <li
                className={
                  steps.step3 ? bookingCSS.booking__headerPaginationActive : ''
                }
              />
              <li
                className={
                  steps.step4 ? bookingCSS.booking__headerPaginationActive : ''
                }
              />
            </ul>
            <span>{title}</span>
          </div>
        </div>
        <div>
          {
            // Flexbox div for centering pagination
          }
        </div>
      </div>
    </>
  );
};

export const AddressModal = ({
  closeAddressValidationModal,
  translations,
  addressModalProps,
  position,
  continueEvent,
  googleApiKey,
}): JSX.Element => {
  return (
    <>
      <div
        className={bookingCSS.booking__loginClose}
        onClick={closeAddressValidationModal}
      >
        <CloseSVG className={bookingCSS.booking__closeLogo} />
      </div>
      <div className={bookingCSS.booking__mapTitle}>
        {translations.mapTitle}
      </div>
      <div className={bookingCSS.booking__mapContainer}>
        <div className={bookingCSS.booking__mapAddress}>
          {translations.mapText}
        </div>
        <div className={bookingCSS.booking__mapAddress}>
          {addressModalProps.address?.street +
            ' ' +
            addressModalProps.address?.streetNr +
            ' ' +
            addressModalProps.address?.zip +
            ' ' +
            addressModalProps.address?.city}
        </div>
        <AddressMap
          position={position}
          googleApiKey={googleApiKey}
          markerName={translations.mapMarkerName}
        />
        <div className={bookingCSS.booking__mapButton}>
          <div className={bookingCSS.booking__mapButtonleft}>
            <Button
              handleClick={closeAddressValidationModal}
              size={'medium'}
              variant={'primary'}
            >
              {translations.editAddressButton}
            </Button>
          </div>
          {position != null && (
            <div className={bookingCSS.booking__mapButtonright}>
              <Button
                handleClick={(): void => {
                  addressModalProps.isValidAddressCallback();
                  closeAddressValidationModal();
                  setTimeout(() => {
                    continueEvent();
                  }, 0);
                }}
                size={'medium'}
                variant={'primary'}
              >
                {translations.useAddressButton}
              </Button>
            </div>
          )}
        </div>
      </div>
    </>
  );
};

export const LoginModal = ({
  LoginForm,
  title,
  closeLoginModal,
  handlePasswordForgot,
}): JSX.Element => {
  return (
    <div>
      <div className={bookingCSS.booking__loginCloseContainer}>
        <div
          className={bookingCSS.booking__loginClose}
          onClick={closeLoginModal}
        >
          <CloseSVG className={bookingCSS.booking__closeLogo} />
        </div>
      </div>
      <div className={bookingCSS.booking__loginTitle}>{title}</div>
      <div className={bookingCSS.booking__loginForm}>
        <LoginForm
          onLogin={(): void => {
            closeLoginModal();
          }}
          handlePasswordForgot={handlePasswordForgot}
        />
      </div>
    </div>
  );
};

export const RegisterModal = ({
  RegisterForm,
  title,
  closeRegisterModal,
  token,
  successText,
  closeText,
}): JSX.Element => {
  const [isSuccessful, setIsSuccessful] = useState(false);

  return (
    <div>
      <div className={bookingCSS.booking__loginCloseContainer}>
        <div
          className={bookingCSS.booking__loginClose}
          onClick={closeRegisterModal}
        >
          <CloseSVG className={bookingCSS.booking__closeLogo} />
        </div>
      </div>
      <div className={bookingCSS.booking__loginTitle}>{title}</div>
      <div className={bookingCSS.booking__loginForm}>
        {!isSuccessful ? (
          <RegisterForm
            token={token}
            onRegister={(): void => {
              setIsSuccessful(true);
            }}
          />
        ) : (
          <>
            <div className={bookingCSS.booking__successText}>{successText}</div>
            <Button
              handleClick={closeRegisterModal}
              size={'medium'}
              variant={'primary'}
            >
              {closeText}
            </Button>
          </>
        )}
      </div>
    </div>
  );
};

export const PasswordResetModal = ({
  PasswordResetForm,
  title,
  closePasswordResetModal,
  handleAlreadyRegistered,
}): JSX.Element => {
  return (
    <div>
      <div className={bookingCSS.booking__loginCloseContainer}>
        <div
          className={bookingCSS.booking__loginClose}
          onClick={closePasswordResetModal}
        >
          <CloseSVG className={bookingCSS.booking__closeLogo} />
        </div>
      </div>
      <div className={bookingCSS.booking__loginTitle}>{title}</div>
      <div className={bookingCSS.booking__loginForm}>
        <PasswordResetForm
          onPasswordReset={(): void => {
            closePasswordResetModal();
          }}
          handleAlreadyRegistered={handleAlreadyRegistered}
        />
      </div>
    </div>
  );
};

export const SummaryContent = ({
  translations,
  isUk,
  locale,
  serviceDetailsData,
  serviceBillingData,
  draftServiceCall,
  isMilaFriend,
}): JSX.Element => {
  return (
    <>
      <span className={bookingCSS.booking__contentTitle}>
        {translations.summary}
      </span>
      <div className={bookingCSS.booking__summaryWrapper}>
        {!serviceDetailsData?.isFlexibleCheckbox && (
          <>
            <div className={bookingCSS.booking__summary}>
              <div className={bookingCSS.booking__summaryHeading}>
                {translations.dateTime}
              </div>
              <div className={bookingCSS.booking__summaryContent}>
                {new Intl.DateTimeFormat(isUk ? 'en-UK' : locale, {
                  weekday: 'long',
                  month: 'long',
                  year: 'numeric',
                  day: '2-digit',
                  hour: '2-digit',
                  minute: '2-digit',
                }).format(serviceDetailsData?.date)}
              </div>
            </div>
            <div className={bookingCSS.booking__summaryDivider} />
          </>
        )}
        <div className={bookingCSS.booking__summary}>
          <div className={bookingCSS.booking__summaryHeading}>
            {translations.serviceLocation}
          </div>
          <div className={bookingCSS.booking__summaryContent}>
            {serviceBillingData.additional && (
              <div>{serviceBillingData.additional}</div>
            )}
            <div>
              {serviceBillingData?.street + ' ' + serviceBillingData?.streetNr}
            </div>
            <div>
              {serviceBillingData?.zip + ' ' + serviceBillingData?.city}
            </div>
            <div>{serviceBillingData?.country}</div>
          </div>
        </div>
        <div className={bookingCSS.booking__summaryDivider} />
        <div className={bookingCSS.booking__summary}>
          <div className={bookingCSS.booking__summaryContent}>
            {draftServiceCall.servicePackages.map((sp, i) => {
              return (
                <div key={i} className={bookingCSS.booking__summaryTotal}>
                  <div>{sp.name}</div>
                  <div>
                    {sp.price.toFixed(2)}
                    &nbsp;{draftServiceCall.currency}
                    {isMilaFriend ? <>&nbsp;*</> : ''}
                  </div>
                </div>
              );
            })}
            {draftServiceCall.vouchers.map((voucher, i) => {
              return (
                <div key={i} className={bookingCSS.booking__summaryTotal}>
                  <div>
                    {translations.voucher} ({voucher.code})
                  </div>
                  <div style={{ paddingRight: isMilaFriend ? '1.5ex' : '' }}>
                    - {voucher.calculatedDiscountAmount.toFixed(2)}
                    &nbsp;{draftServiceCall.currency}
                  </div>
                </div>
              );
            })}
            {draftServiceCall.priceHappinessGuaranteeDiscounted ? (
              <div className={bookingCSS.booking__summaryTotal}>
                <div>{translations.priceHappiness}</div>
                <div style={{ paddingRight: isMilaFriend ? '1.5ex' : '' }}>
                  {draftServiceCall.priceHappinessGuaranteeDiscounted.toFixed(
                    2,
                  )}
                  &nbsp;{draftServiceCall.currency}
                </div>
              </div>
            ) : (
              <></>
            )}
            <div className={bookingCSS.booking__summaryTotal}>
              <div>{translations.total}</div>
              <div>
                {`${draftServiceCall.priceDiscounted.toFixed(2)} ${
                  draftServiceCall.currency
                } ${isMilaFriend ? '*' : ''}`}
              </div>
            </div>
          </div>
        </div>
        <div className={bookingCSS.booking__summaryInfo}>
          {isMilaFriend && translations.summaryInfo}
        </div>
      </div>
    </>
  );
};

export const SummaryGiftCard = ({
  translations,
  serviceBillingData,
  amount,
  isPdf,
  currencyCode,
}): JSX.Element => {
  return (
    <>
      <span className={bookingCSS.booking__contentTitle}>
        {translations.summary}
      </span>
      <div className={bookingCSS.booking__summaryWrapper}>
        <div className={bookingCSS.booking__summary}>
          <div className={bookingCSS.booking__summaryHeading}>
            {translations.serviceLocation}
          </div>
          <div className={bookingCSS.booking__summaryContent}>
            {serviceBillingData.additional && (
              <div>{serviceBillingData.additional}</div>
            )}
            <div>
              {serviceBillingData?.street + ' ' + serviceBillingData?.streetNr}
            </div>
            <div>
              {serviceBillingData?.zip + ' ' + serviceBillingData?.city}
            </div>
            <div>{serviceBillingData?.country}</div>
          </div>
        </div>
        <div className={bookingCSS.booking__summaryDivider} />
        <div className={bookingCSS.booking__summary}>
          <div className={bookingCSS.booking__summaryContent}>
            <div className={bookingCSS.booking__summaryTotal}>
              <div>Gift Card</div>
              <div>{getAmountWithCurrency(amount, currencyCode)}</div>
            </div>

            {!isPdf ? (
              <div className={bookingCSS.booking__summaryTotal}>
                <div>
                  {translations.shipping.replace('+ ', '').split(':')[0]}
                </div>
                <div>{getAmountWithCurrency(3, currencyCode)}</div>
              </div>
            ) : (
              <></>
            )}

            <div className={bookingCSS.booking__summaryTotal}>
              <div>{translations.total}</div>
              <div>
                {getAmountWithCurrency(
                  isPdf ? amount : amount + 3,
                  currencyCode,
                )}
              </div>
            </div>
          </div>
        </div>
        <div className={bookingCSS.booking__summaryInfo} />
      </div>
    </>
  );
};
