import React, { createContext, useContext, useState, useEffect } from 'react';
import Cookies from 'js-cookie';

import classNames from 'classnames/bind';
import TextItem from 'components/items/TextItem';
import styleIdentifiers from './CookiesPreferences.module.scss';

const styles = classNames.bind(styleIdentifiers);

export interface CookiesPreferences {}

/**
 * Example
 * <CookieContextProvider>
 *    <CookieBanner
 *      title="Your privacy matter"
 *      message="This site uses cookies to offer you a better browsing experience. By accepting, you consent to the use of cookies"
 *      policyText="To find out more, read our updated policy terms in the link	"
 *      policyLinkText="Cookie Policy"
 *      acceptButtonText="Ok"
 *      manageConsentText="Manage cookie preferences"
 *    >
 *      <CookieDialog>
 *        <PreferenceCheckbox onPreferenceToggle={preferenceToggle} />
 *        <MarketingCheckbox onMarketingToggle={preferenceToggle} />
 *        <StatisticsCheckbox onStatisticsToggle={preferenceToggle} />
 *      </CookieDialog>
 *    </CookieBanner>
 *  </CookieContextProvider>
 */
/** *****************
 * Context API
 ***************** */

export const CookieContext = createContext();

export const CookieContextProvider = props => {
  const { children } = props;
  const [isDialogOpen, setDialogState] = useState(false);
  const [isBannerOpen, setBannerState] = useState(false);

  return <CookieContext.Provider value={{ isDialogOpen, setDialogState, isBannerOpen, setBannerState }}>{children}</CookieContext.Provider>;
};

export const CookieBanner = props => {
  const { name, title, message, policyText, policyLink, policyLinkText, cssClass, acceptButtonText, manageConsentText, children } = props;
  const { setDialogState, isBannerOpen, setBannerState } = useContext(CookieContext);

  useEffect(() => {
    if (Cookies.get(name)) setBannerState(false);
    else setBannerState(true);
  });

  const acceptCookies = () => {
    Cookies.set(name, 'true');
    setBannerState(false);
  };

  const manageConsent = () => {
    setDialogState(true);
  };

  return (
    <>
      <div id="cookie-bar" className={styles('cookie-consent-banner', isBannerOpen ? 'is-active' : '', cssClass)}>
        <div className={styles('policy-info')}>
          <h2 className={styles('title')}>{title}</h2>
          <p className={styles('description')}>
            <span>{message}</span>
            <span>{policyText}</span>
            &nbsp;
            <a href={policyLink}>{policyLinkText}</a>
          </p>
        </div>
        <div className={styles('cta-actions')}>
          <button type="button" onClick={acceptCookies}>
            {acceptButtonText}
          </button>
          <button type="button" onClick={manageConsent}>
            {manageConsentText}
          </button>
        </div>
      </div>
      {children}
    </>
  );
};

CookieBanner.defaultProps = {
  name: 'necessary-cookies',
  title: 'Your privacy',
  message: 'This site uses cookies to offer you a better browsing experience. By accepting, you consent to the use of cookies.',
  policyText: 'To find out more, read our updated policy terms in the link',
  policyLinkText: 'Cookie Policy',
  policyLink: 'https://gdpr.eu/cookies/',
  acceptButtonText: 'I am OK with it',
  manageConsentText: 'Manage Preferences',
  cssClass: '',
};

export const CookieDialog = props => {
  const { title, message, confirmText, cancelText, cssClass, children } = props;

  const { isDialogOpen, setDialogState } = useContext(CookieContext);

  useEffect(() => {}, []);

  // Events
  //--------

  const closeDialog = e => {
    e.preventDefault();
    setDialogState(false);
  };

  // Functions
  //----------

  return (
    <>
      <div className={styles('cookie-preference-dialog', isDialogOpen ? 'is-visible' : '', cssClass)}>
        <div className={styles('container')}>
          <h1>{title}</h1>
          <p>{message}</p>
          {children}
          <div className={styles('button-actions')}>
            <button type="button" onClick={closeDialog}>
              {confirmText}
            </button>
            <button type="button" onClick={closeDialog}>
              {cancelText}
            </button>
          </div>
        </div>
      </div>
      <div className={styles('body-overlay', isDialogOpen ? 'is-visible' : '')} />
    </>
  );
};

CookieDialog.defaultProps = {
  title: 'Your privacy options',
  message: 'Please review and manage your privacy settings below',
  cssClass: 'css',
  confirmText: 'Save Preferences',
  cancelText: 'Cancel',
};

export const PreferenceCheckbox = props => {
  const { name, title, message } = props;

  const [preferenceCookie, setPreferenceCookie] = useState(true);

  useEffect(() => {
    if (Cookies.get(name)) setPreferenceCookie(true);
    else setPreferenceCookie(false);
  }, []);

  const togglePreferenceCookie = e => {
    setPreferenceCookie(e.target.checked);

    if (e.target.checked) {
      Cookies.set(props.name, e.target.checked);
    } else {
      Cookies.remove(props.name);
    }

    // callback with checkbox status if necessary
    props.onPreferenceToggle(e.target.checked);
  };

  return (
    <div className={styles('cookie-options-wrapper')}>
      <h3 className={styles('title')}>{title}</h3>

      <div className={styles('cookie-option')}>
        <div className={styles('checkbox-control')}>
          <label className={styles('checkbox-container')}>
            <input type="checkbox" checked={preferenceCookie} onChange={togglePreferenceCookie} />
            <span className={styles('checkmark')} />
          </label>
        </div>
        <div className={styles('description')}>
          <p>{message}</p>
        </div>
      </div>
    </div>
  );
};

export const MarketingCheckbox = props => {
  const { name, title, message } = props;

  const [marketingCookie, setMarketingCookie] = useState(true);

  useEffect(() => {
    if (Cookies.get(name)) setMarketingCookie(true);
    else setMarketingCookie(false);
  }, []);

  const toggleMarketingCookie = e => {
    setMarketingCookie(e.target.checked);

    if (e.target.checked) {
      Cookies.set(props.name, e.target.checked);
    } else {
      Cookies.remove(props.name);
    }

    // callback with checkbox status if necessary
    props.onMarketingToggle(e.target.checked);
  };

  return (
    <div className={styles('cookie-options-wrapper')}>
      <h3 className={styles('title')}>{title}</h3>

      <div className={styles('cookie-option')}>
        <div className={styles('checkbox-control')}>
          <label className={styles('checkbox-container')}>
            <input type="checkbox" checked={marketingCookie} onChange={toggleMarketingCookie} />
            <span className={styles('checkmark')} />
          </label>
        </div>
        <div className={styles('description')}>
          <p>{message}</p>
        </div>
      </div>
    </div>
  );
};

export const StatisticsCheckbox = props => {
  const { name, title, message } = props;

  const [statisticsCookie, setStatisticsCookie] = useState(true);

  useEffect(() => {
    if (Cookies.get(name)) setStatisticsCookie(true);
    else setStatisticsCookie(false);
  }, []);

  const toggleStatisticsCookie = e => {
    setStatisticsCookie(e.target.checked);

    if (e.target.checked) {
      Cookies.set(props.name, e.target.checked);
    } else {
      Cookies.remove(props.name);
    }

    // callback with checkbox status if necessary
    props.onStatisticsToggle(e.target.checked);
  };

  return (
    <div className={styles('cookie-options-wrapper')}>
      <h3 className={styles('title')}>{title}</h3>

      <div className={styles('cookie-option')}>
        <div className={styles('checkbox-control')}>
          <label className={styles('checkbox-container')}>
            <input type="checkbox" checked={statisticsCookie} onChange={toggleStatisticsCookie} />
            <span className={styles('checkmark')} />
          </label>
        </div>
        <div className={styles('description')}>
          <p>{message}</p>
        </div>
      </div>
    </div>
  );
};

PreferenceCheckbox.defaultProps = {
  title: 'Preference Cookie',
  message: 'This cookie option manages and tracks some marketing data',
  name: 'preference_cookie',
  expiry: 365,
  onPreferenceToggle() {},
};

MarketingCheckbox.defaultProps = {
  title: 'Marketing Cookie',
  message: 'This cookie option manages and tracks some marketing data',
  name: 'marketing_cookie',
  expiry: 365,
  onMarketingToggle() {},
};

StatisticsCheckbox.defaultProps = {
  title: 'Statistics Cookie',
  message: 'This cookie option manages and tracks some marketing data',
  name: 'statistics_cookie',
  expiry: 365,
  onStatisticsToggle() {},
};
