import React, { FC, ReactType, useEffect, useState } from 'react';
import Layout from '../../components/Layout';
import css from './index.module.css';
import bookingCSS from '../BookingFunnel/index.module.css';
import { Button, Link, LinkProps } from '../../index';
import LogoRawSVG from '../../assets/icons/logo-raw.svg';
import ServiceStep1 from '../../assets/icons/service-step1.svg';
import ServiceStep2 from '../../assets/icons/service-step2.svg';
import ServiceStep3 from '../../assets/icons/service-step3.svg';
import ServiceStep4 from '../../assets/icons/service-step4.svg';
import Textarea from '../../blocks/Textarea';
import format from 'date-fns/format';
import { createEvent } from 'ics';
import { RegisterModal } from '../../helpers/bookingFunnelHelper';
import ReactModal from 'react-modal';

export interface ConfirmationPageProps {
  logoLink?: LinkProps;
  translations: {
    title: string;
    subtitle: string;
    bookingSuccessful: string;
    touch?: {
      title: string;
      text: string;
    };
    servicePerformance?: {
      title: string;
      text: string;
    };
    payment?: {
      title: string;
      text: string;
    };
    appointment: string;
    calendar: string;
    feedback?: {
      title: string;
      text: string;
      rating: string;
      specific: string;
      send: string;
      success: string;
    };
    account?: {
      title: string;
      text: string;
      signUp: string;
    };
    home: string;
    register: string;
    registerSuccessful: string;
    close: string;
  };
  isLoggedIn: boolean;
  servicePackage: {
    name: string;
    description: string;
    duration: string;
  };
  locale: string;
  bookingData: {
    serviceDetailsData: {
      date: Date;
      isFlexibleCheckbox: boolean;
    };
    serviceLocationData: {
      street: string;
      streetNr: string;
      zip: string;
      city: string;
      firstName: string;
      lastName: string;
    };
  };
  createBookingFeedback: (rating: number, feedback: string) => Promise<void>;
  FormRegister: ReactType;
  passwordToken: string;
}

const ConfirmationPage: FC<ConfirmationPageProps> = ({
  logoLink,
  translations,
  isLoggedIn,
  servicePackage,
  locale,
  bookingData,
  createBookingFeedback,
  FormRegister,
  passwordToken,
}) => {
  const isUk = locale.slice(3, 5).toLowerCase() === 'gb';
  const [rating, setRating] = useState(0);
  const [feedback, setFeedback] = useState(null);
  const [isSubmitted, setIsSubmitted] = useState(false);
  const bookingDate = bookingData.serviceDetailsData.date;
  const locationData = bookingData.serviceLocationData;
  const [registerModalIsOpen, setRegisterModalIsOpen] = useState(false);

  const openRegisterModal = (): void => {
    setRegisterModalIsOpen(true);
  };

  const closeRegisterModal = (): void => {
    setRegisterModalIsOpen(false);
  };

  //Declare var as tuple because number[] is not assignable to [number,number] -> ics DateArray
  const dateArray: [number, number, number, number, number] = [0, 0, 0, 0, 0];
  format(bookingDate, 'yyyy-M-d-H-m')
    .split('-')
    .map((x, i) => (dateArray[i] = +x));

  const calendarEvent = createEvent({
    title: `Mila - ${servicePackage.name}`,
    description: servicePackage.description,
    location: `${locationData.street} ${locationData.streetNr}, ${locationData.zip} ${locationData.city}`,
    duration: { minutes: parseInt(servicePackage.duration) },
    start: dateArray,
  });
  const saveCalendar = (): void => {
    const url = window.URL.createObjectURL(new Blob([calendarEvent.value]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', 'Mila-Service.ics');
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };
  useEffect(() => {
    window.scrollTo(0, 0);
  }, []);
  const createRatingButton = (value): JSX.Element => {
    value += 1;
    return (
      <li
        className={`${rating == value ? css.confirmation__active : ''}`}
        key={value}
      >
        <Button
          handleClick={(): void => setRating(value)}
          size={'small'}
          variant={'tertiary'}
        >
          {value}
        </Button>
      </li>
    );
  };

  return (
    <Layout>
      <div className={css.confirmationPage}>
        <div className={css.confirmation__header}>
          <div className={css.confirmation__headerLogoWrapper}>
            <Link
              {...logoLink}
              className={css.confirmation__logoLink}
              aria-label="Back to home"
            >
              <LogoRawSVG className={css.confirmation__headerLogo} />
              <span>Technologie ganz einfach</span>
            </Link>
          </div>
        </div>

        <div className={css.confirmation__content}>
          <div
            className={`${css.confirmation__contentWrap} ${css.confirmation__steps}`}
          >
            <h1 className={css.confirmation__title}>{translations.title}</h1>
            <span className={css.confirmation__subtitle}>
              {translations.subtitle}
            </span>

            <div className={css.confirmation__stepsList}>
              <div className={css.confirmation__step}>
                <div className={css.confirmation__stepIcon}>
                  <ServiceStep1 />
                  <div
                    className={css.confirmation__stepsDivider}
                    style={{ borderLeftStyle: 'solid' }}
                  />
                  <div className={css.confirmation__stepDivider} />
                </div>
                <div className={css.confirmation__stepText}>
                  <p>{servicePackage.name}</p>
                  <p>{translations.bookingSuccessful}</p>
                </div>
              </div>

              <div className={css.confirmation__step}>
                <div className={css.confirmation__stepIcon}>
                  <ServiceStep2 />
                  <div
                    className={css.confirmation__stepsDivider}
                    style={{ borderLeftStyle: 'solid' }}
                  />
                  <div className={css.confirmation__stepDivider} />
                </div>
                <div className={css.confirmation__stepText}>
                  <p>{translations.touch.title}</p>
                  <p>{translations.touch.text}</p>
                </div>
              </div>

              <div className={css.confirmation__step}>
                <div className={css.confirmation__stepIcon}>
                  <ServiceStep3 />
                  <div
                    className={css.confirmation__stepsDivider}
                    style={{ borderLeftStyle: 'solid' }}
                  />
                  <div className={css.confirmation__stepDivider} />
                </div>
                <div className={css.confirmation__stepText}>
                  <p>{translations.servicePerformance.title}</p>
                  <p>{translations.servicePerformance.text}</p>
                </div>
              </div>

              <div className={css.confirmation__step}>
                <div className={css.confirmation__stepIcon}>
                  <ServiceStep4 />
                  <div
                    className={css.confirmation__stepsDivider}
                    style={{ borderLeftStyle: 'solid' }}
                  />
                </div>
                <div className={css.confirmation__stepText}>
                  <p>{translations.payment.title}</p>
                  <p>{translations.payment.text}</p>
                </div>
              </div>
            </div>
          </div>

          {!bookingData.serviceDetailsData.isFlexibleCheckbox && (
            <div
              className={`${css.confirmation__contentWrap} ${css.confirmation__calendar}`}
            >
              <span>{translations.appointment}</span>
              <span className={css.confirmation__calendarDate}>
                {new Intl.DateTimeFormat(isUk ? 'en-UK' : locale, {
                  weekday: 'short',
                  month: 'long',
                  day: '2-digit',
                  hour: '2-digit',
                  minute: '2-digit',
                }).format(bookingData.serviceDetailsData.date)}
              </span>
              <Button
                size={'small'}
                variant={'tertiary'}
                handleClick={(): void => {
                  saveCalendar();
                }}
              >
                {translations.calendar}
              </Button>
            </div>
          )}

          <div className={css.confirmation__contentWrap}>
            {isSubmitted ? (
              <h3>{translations.feedback.success}</h3>
            ) : (
              <>
                <h3>{translations.feedback.title}</h3>
                <span>{translations.feedback.text}</span>
                <span>{translations.feedback.rating}</span>

                <div className={css.confirmation__rating}>
                  <ul>
                    {Array(10)
                      .fill(1)
                      .map((el, i) => createRatingButton(i))}
                  </ul>
                </div>

                {rating > 0 && (
                  <form action="" className={css.confirmation__ratingForm}>
                    <div>
                      <Textarea
                        style={'booking'}
                        label={translations.feedback.specific}
                        initialRows={2}
                        name="feedback"
                        onChange={(e): void => {
                          setFeedback(e.target.value);
                        }}
                        required={false}
                        placeholder={translations.feedback.specific}
                        optional={true}
                      />
                    </div>
                    <Button
                      handleClick={(): void => {
                        setIsSubmitted(true);
                        createBookingFeedback(rating, feedback);
                      }}
                      size={'small'}
                      variant={'primary'}
                    >
                      {translations.feedback.send}
                    </Button>
                  </form>
                )}
              </>
            )}
          </div>

          {!isLoggedIn && (
            <>
              <div
                className={`${css.confirmation__contentWrap} ${css.confirmation__account}`}
              >
                <h3>{translations.account.title}</h3>
                <p>{translations.account.text}</p>
                <Button
                  size={'small'}
                  variant={'tertiary'}
                  handleClick={openRegisterModal}
                >
                  {translations.account.signUp}
                </Button>
              </div>
            </>
          )}
          <ReactModal
            isOpen={registerModalIsOpen}
            className={bookingCSS.booking__overlay}
            overlayClassName={bookingCSS.booking__modal}
            ariaHideApp={false}
            onRequestClose={closeRegisterModal}
          >
            <RegisterModal
              token={passwordToken}
              RegisterForm={FormRegister}
              title={translations.register}
              successText={translations.registerSuccessful}
              closeRegisterModal={closeRegisterModal}
              closeText={translations.close}
            />
          </ReactModal>

          {isLoggedIn && (
            <div
              className={`${css.confirmation__contentWrap} ${css.confirmation__account}`}
            >
              <Link title={translations.home} to={'/'}>
                <Button variant={'tertiary'}>{translations.home}</Button>
              </Link>
            </div>
          )}
        </div>
      </div>
    </Layout>
  );
};

export default ConfirmationPage;
