text: import React, { useState } from 'react';
  import { useDispatch, useSelector } from 'react-redux';
  import { useHistory } from 'react-router-dom';
  import { Col, Row } from 'reactstrap';
  import styled from 'styled-components';
  import i18n from 'i18next';
  
  import { ReactComponent as EyeIcon } from 'assets/icon-visible.svg';
  import AuthHeader from 'shared/components/layout/AuthHeader';
  import Footer from 'shared/components/layout/Footer';
  import { Button } from 'shared/components/Buttons';
  import { colors, logos } from 'shared/defaultTheme';
  import AlertModal from 'shared/components/AlertModal';
  import MainSpinner from 'shared/components/MainSpinner';
  
  import useApi from 'hooks/useApi';
  import { changeTheme } from 'redux/actions/themeActions';
  import { ALERT_TYPE_ERROR, ALERT_TYPE_SUCCESS } from 'shared/utils';
  
  import ContentCard from './components/ContentCard';
  import Title from './components/Title';
  import BrandGraphicAspectionSection from './components/BrandGraphicAspectSection';
  import SocialNetworksFooterSection from './components/SocialNetworksFooterSection';
  import SendEmailSettingsSection from './components/SendEmailSettingsSection';
  import ModalPreview from './components/ModalPreview';
  import PreviewNotification from './components/PreviewNotifications';
  import PreviewExternalSite from './components/PreviewExternalSite';
  
  const GeneralCustomizer = () => {
    const theme = useSelector((state) => state.theme);
    const auth = useSelector((state) => state.auth);
    const history = useHistory();
    const dispatch = useDispatch();
    const api = useApi();
    const [selectedMainColor, setSelectedMainColor] = useState();
    const [selectedSecondaryColor, setSelectedSecondaryColor] = useState();
    const [selectedPageHeaderOption, setSelectedPageHeaderOption] = useState();
    const [selectedPageFooterOption, setSelectedPageFooterOption] = useState();
    const [selectedLogoBase4, setSelectedLogoBase4] = useState();
    const [selectedLogoFooterBase4, setSelectedLogoFooterBase4] = useState();
    const [selectedFavicoBase4, setSelectedFavicoBase4] = useState();
    const [selectedNotificationImg, setSelectedNotificationImg] = useState();
    const [showLogoFooter, setShowLogoFooter] = useState(true);
    const [footerText, setFooterText] = useState('');
    const [youtubeLink, setYoutubeLink] = useState('');
    const [twitterLink, setTwitterLink] = useState('');
    const [facebookLink, setFacebookLink] = useState('');
    const [linkedinLink, setLinkedinLink] = useState('');
    const [phone, setPhone] = useState('');
    const [activeCustomEmail, setActiveCustomEmail] = useState(true);
    const [server, setServer] = useState('');
    const [port, setPort] = useState('');
    const [user, setUser] = useState('');
    const [pass, setPass] = useState('');
    const [safeConnection, setSafeConnection] = useState(true);
    const [openPreviewNotification, setOpenPreviewNotification] = useState(false);
    const [openPreviewExternalSite, setOpenPreviewExternalSite] = useState(false);
    const [openAlert, setOpenAlert] = useState(false);
    const [alertType, setAlertType] = useState(ALERT_TYPE_SUCCESS);
    const [alertMessage, setAlertMessage] = useState('');
  
    const [{ loading: loadingModify }, modifyCustomer] = api(
      {
        url: 'cus/customers/modify',
        method: 'POST',
      },
      { manual: true }
    );
    const [{ loading: loadingConfig }, modifyConfig] = api(
      {
        url: `cus/customers/${auth.cusNavId}/modify/configuration`,
        method: 'POST',
      },
      { manual: true }
    );
    const [{ loading: loadingSmtp }, modifySmtp] = api(
      {
        url: `cus/customers/${auth.cusNavId}/modify/smtp`,
        method: 'POST',
      },
      { manual: true }
    );
  
    const onToggleModalPreviewNotification = () =>
      setOpenPreviewNotification(!openPreviewNotification);
  
    const onToggleModalPreviewExternalSite = () =>
      setOpenPreviewExternalSite(!openPreviewExternalSite);
  
    const showAlert = (type, message) => {
      setAlertType(type);
      setAlertMessage(message);
      setOpenAlert(true);
    };
  
    const closeAlert = () => {
      if (alertType === ALERT_TYPE_ERROR) {
        setAlertType(ALERT_TYPE_SUCCESS);
        setAlertMessage('');
        setOpenAlert(false);
        return;
      }
      history.push('/home');
    };
  
    const validateRequiredData = () => {
      const errors = [];
      if (!selectedLogoBase4) {
        errors.push(i18n.t('general_customizer_logo_required'));
      }
      if (!selectedLogoFooterBase4) {
        errors.push(i18n.t('general_customizer_logo_footer_required'));
      }
      if (!selectedFavicoBase4) {
        errors.push(i18n.t('general_customizer_favicon_requried'));
      }
      if (!selectedMainColor) {
        errors.push(i18n.t('general_customizer_main_color_required'));
      }
      if (!selectedSecondaryColor) {
        errors.push(i18n.t('general_customizer_secondary_color_required'));
      }
      if (!selectedNotificationImg) {
        errors.push(i18n.t('general_customizer_notification_image_required'));
      }
  
      if (activeCustomEmail) {
        if (!server.length) {
          errors.push(i18n.t('general_customizer_outbound_server_required'));
        }
        if (!port.length) {
          errors.push(i18n.t('general_customizer_port_required'));
        }
        if (!user.length) {
          errors.push(i18n.t('general_customizer_user_required'));
        }
        if (!pass.length) {
          errors.push(i18n.t('general_customizer_password_required'));
        }
      }
  
      return errors;
    };
  
    const onClean = () => {
      setSelectedMainColor(undefined);
      setSelectedSecondaryColor(undefined);
      setSelectedPageHeaderOption(undefined);
      setSelectedPageFooterOption(undefined);
      setSelectedLogoBase4(undefined);
      setSelectedLogoFooterBase4(undefined);
      setSelectedNotificationImg(undefined);
      setShowLogoFooter(true);
      setFooterText('');
      setYoutubeLink('');
      setTwitterLink('');
      setFacebookLink('');
      setLinkedinLink('');
      setPhone('');
      setActiveCustomEmail(true);
      setServer('');
      setPort('');
      setUser('');
      setPass('');
      setSafeConnection(true);
    };
  
    const onSave = async () => {
      try {
        const validationErrors = validateRequiredData();
        if (validationErrors.length) {
          showAlert(ALERT_TYPE_ERROR, validationErrors.join(', '));
          return;
        }
        const {
          data: { errors: modifyCustomerError },
        } = await modifyCustomer({
          data: {
            clientNavision: auth.cusNavId,
            domains: [
              {
                type: 'external',
                url: window.location.origin,
                mail: '',
              },
            ],
          },
        });
        if (modifyCustomerError.length) {
          throw new Error('error throw by modify customer data');
        }
        const configData = {
          logo: selectedLogoBase4,
          logoFooter: selectedLogoFooterBase4,
          logoNotify: selectedNotificationImg,
          favicon: selectedFavicoBase4,
          colorPpal: selectedMainColor,
          colorSec: selectedSecondaryColor,
          header: selectedPageHeaderOption,
          footer: selectedPageFooterOption,
          phone,
          info: footerText,
          linkYoutube: youtubeLink,
          linkTwitter: twitterLink,
          linkFacebook: facebookLink,
          linkLinkedin: linkedinLink,
        };
        const {
          data: { errors: configErrors },
        } = await modifyConfig({
          data: configData,
        });
        if (configErrors.length) {
          throw new Error('error throw by modify config');
        }
        if (activeCustomEmail) {
          const smtpData = {
            server,
            port,
            user,
            account: user,
            pass,
            ssl: safeConnection,
            tsl: false,
          };
          const {
            data: { errors: smtpErrors },
          } = await modifySmtp({
            data: smtpData,
          });
          if (smtpErrors.length) {
            throw new Error('error throw by modify smtp');
          }
        }
        dispatch(changeTheme(configData));
        showAlert(ALERT_TYPE_SUCCESS, i18n.t('general_customizer_success_message'));
      } catch (ex) {
        console.error('saving customer config: ', ex);
        showAlert(ALERT_TYPE_ERROR, i18n.t('general_error_message'));
      }
    };
  
    const { mainColor, secondaryColor } = theme;
    return (
      <div className="general-customizer">
        <AuthHeader
          className="general-customizer__header"
          logoSrc={logos.lefebvreWhite}
          backgroundColor={mainColor}
          withBottomBar={false}
        />
        <div className="general-customizer__container">
          <ContentCard>
            <Title color={mainColor} />
            <div className="general-customizer_content">
              <Subtitle className="general-customizer_content_subtitle" color={mainColor}>
                {i18n.t('general_customizer_desc')}
              </Subtitle>
              <BrandGraphicAspectionSection
                mainColor={mainColor}
                selectedLogoBase4={selectedLogoBase4}
                setSelectedLogoBase4={setSelectedLogoBase4}
                selectedMainColor={selectedMainColor}
                setSelectedMainColor={setSelectedMainColor}
                selectedSecondaryColor={selectedSecondaryColor}
                setSelectedSecondaryColor={setSelectedSecondaryColor}
                selectedPageHeaderOption={selectedPageHeaderOption}
                setSelectedPageHeaderOption={setSelectedPageHeaderOption}
                selectedPageFooterOption={selectedPageFooterOption}
                setSelectedPageFooterOption={setSelectedPageFooterOption}
                selectedLogoFooterBase4={selectedLogoFooterBase4}
                setSelectedLogoFooterBase4={setSelectedLogoFooterBase4}
                selectedFavicoBase4={selectedFavicoBase4}
                setSelectedFavicoBase4={setSelectedFavicoBase4}
              />
              <SocialNetworksFooterSection
                mainColor={mainColor}
                showLogoFooter={showLogoFooter}
                setShowLogoFooter={setShowLogoFooter}
                youtubeLink={youtubeLink}
                setYoutubeLink={setYoutubeLink}
                twitterLink={twitterLink}
                setTwitterLink={setTwitterLink}
                facebookLink={facebookLink}
                setFacebookLink={setFacebookLink}
                linkedinLink={linkedinLink}
                setLinkedinLink={setLinkedinLink}
                footerText={footerText}
                setFooterText={setFooterText}
                phone={phone}
                setPhone={setPhone}
              />
              <SendEmailSettingsSection
                mainColor={mainColor}
                selectedNotificationImg={selectedNotificationImg}
                setSelectedNotificationImg={setSelectedNotificationImg}
                activeCustomEmail={activeCustomEmail}
                setActiveCustomEmail={setActiveCustomEmail}
                server={server}
                setServer={setServer}
                port={port}
                setPort={setPort}
                user={user}
                setUser={setUser}
                pass={pass}
                setPass={setPass}
                safeConnection={safeConnection}
                setSafeConnection={setSafeConnection}
              />
            </div>
            <Row className="general-customizer__footer_content">
              <Col xl={6} lg={6} className="d-flex flex-row justify-content-start align-items-center">
                <Button
                  className="general-customizer__button-preview"
                  label={i18n.t('general_customizer_button_notification_preview')}
                  color="secondary"
                  type="button"
                  onClick={onToggleModalPreviewNotification}
                  icon={<EyeIcon fill={secondaryColor} />}
                  textColor={secondaryColor}
                />
                <Button
                  className="general-customizer__button-preview"
                  label={i18n.t('general_customizer_button_external_page_preview')}
                  color="secondary"
                  type="button"
                  onClick={onToggleModalPreviewExternalSite}
                  icon={<EyeIcon fill={colors.ecru} />}
                  textColor={secondaryColor}
                />
              </Col>
              <Col xl={6} lg={6} className="d-flex flex-row justify-content-end align-items-center">
                <Button
                  className="general-customizer__footer-button general-customizer__footer-button--space"
                  label={i18n.t('general_button_cancel')}
                  color="secondary"
                  type="button"
                  onClick={() => null}
                  textColor={mainColor}
                />
                <Button
                  className="general-customizer__footer-button general-customizer__footer-button--space"
                  label={i18n.t('general_button_clean')}
                  color="secondary"
                  type="button"
                  onClick={onClean}
                  textColor={mainColor}
                />
                <Button
                  className="general-customizer__footer-button"
                  label={i18n.t('general_button_save')}
                  color="primary"
                  type="button"
                  onClick={onSave}
                  backgroundColor={mainColor}
                />
              </Col>
            </Row>
            <ModalPreview isOpen={openPreviewNotification} toggle={onToggleModalPreviewNotification}>
              <PreviewNotification
                logo={selectedLogoBase4}
                mainColor={selectedMainColor}
                footerLogo={selectedLogoFooterBase4}
                footerText={footerText}
                phone={phone}
                selectedNotificationImg={selectedNotificationImg}
              />
            </ModalPreview>
            <ModalPreview isOpen={openPreviewExternalSite} toggle={onToggleModalPreviewExternalSite}>
              <PreviewExternalSite
                logo={selectedLogoBase4}
                mainColor={selectedMainColor}
                secondaryColor={selectedSecondaryColor}
                footerOption={selectedPageFooterOption}
                footerLogo={selectedLogoFooterBase4}
                footerText={footerText}
                phone={phone}
              />
            </ModalPreview>
          </ContentCard>
        </div>
        <Footer
          logoSrc={theme.logoFooter}
          backgroundColor={theme.backgroundFooter}
          footerText={theme.footerText}
          iconColor={theme.footerIconColor}
          facebookLink={theme.facebookLink}
          linkedinLink={theme.linkedinLink}
          youtubeLink={theme.youtubeLink}
          twitterLink={theme.twitterLink}
        />
        <AlertModal
          type={alertType}
          isOpen={openAlert}
          toggle={closeAlert}
          message={alertMessage}
          okText={i18n.t('general_button_ok')}
          onOk={closeAlert}
        />
        {(loadingModify || loadingConfig || loadingSmtp) && <MainSpinner />}
      </div>
    );
  };
  
  const Subtitle = styled.h1(({ color }) => ({
    color,
  }));
  
  export default GeneralCustomizer;
  