// @flow
import React, { useState } from 'react';
import { useCookies } from 'react-cookie';

import {
  ContentWrapper,
  TitleWrapper,
  BottomWrapper,
  ButtonsWrapper,
  PersonaliseWrapper,
  Title,
  Button,
  Summary,
  PersonaliseLink,
} from './CookieBannerStylingComponents';

const cookiesExpiry = new Date(Date.now() + 12 * 30 * 24 * 60 * 60 * 1000);

const CookieBanner = () => {
  const [cookies, setCookie, removeCookie] = useCookies(['cookie-banner']);
  const [showCookieBanner, setShowCookieBanner] = useState(!cookies['cookie-banner']);

  const handleAcceptAll = () => {
    setCookie('cookie-banner', true, { path: '/', expires: cookiesExpiry });
    setCookie('performance-cookie-consent', true, { path: '/', expires: cookiesExpiry, domain: '.apolitical.co' });
    setCookie('functional-cookie-consent', true, { path: '/', expires: cookiesExpiry });
    setShowCookieBanner(false);
    window.location.reload();
  };

  const handleRejectAll = () => {
    setCookie('cookie-banner', true, { path: '/', expires: cookiesExpiry });
    removeCookie('performance-cookie-consent');
    removeCookie('functional-cookie-consent');
    setShowCookieBanner(false);
  };

  if (!showCookieBanner) {
    return null;
  }

  return (
    <ContentWrapper>
      <TitleWrapper>
        <Title>Cookies and your privacy <span role="img" aria-label="cookie">🍪</span></Title>
      </TitleWrapper>
      <BottomWrapper>
        <Summary>
          We take your trust and privacy very seriously. Apolitical uses safe cookies
          (small files on your device) to run the site.
          You can reject non-essential cookies, but some site features may not work without them.
        </Summary>
        <ButtonsWrapper>
          <Button
            type="Button"
            onClick={handleRejectAll}
            className="gtm-trackable"
            data-gtm-event-context="cookie-banner"
            data-gtm-event-type="cookie-reject-all-click"
          >
            Reject all
          </Button>
          <Button
            type="Button"
            onClick={handleAcceptAll}
            className="gtm-trackable"
            data-gtm-event-context="cookie-banner"
            data-gtm-event-type="cookie-accepted-all-click"
          >
            Accept all
          </Button>
        </ButtonsWrapper>
        <PersonaliseWrapper>
          <PersonaliseLink
            href="/pages/cookie-policy"
            className="gtm-trackable"
            data-gtm-event-context="cookie-banner"
            data-gtm-event-type="cookie-policy-page-click"
          >
            Change my settings
          </PersonaliseLink>
        </PersonaliseWrapper>
      </BottomWrapper>
    </ContentWrapper>
  );
};

export default CookieBanner;
