import React, { Component } from "react";
import "./sidebar.css";
import { Link, withRouter, } from "react-router-dom";
import { Row, Col, Container, Button } from 'react-bootstrap'

import Modal from 'react-modal'

import DisenoSidebarPage        from "./diseno.sidebar.page";
import DatosContactoSidebarPage from "./datosContacto.sidebar.page";
import PortadaSidebarPage  from "./portada.sidebar.page";
import IntroduccionSidebarPage  from "./introduccion.sidebar.page";
import DescripcionSidebarPage  from "./descripcion.sidebar.page";
import ContactoSidebarPage  from "./contacto.sidebar.page";
import CarreteSidebarPage  from "./carrete.sidebar.page";
import DocumentosSidebarPage  from "./documentos.sidebar.page";
import UbicacionSidebarPage from "./ubicacion.sidebar.page";
import RedesSidebarPage from "./redes.sidebar.page";
import OpinionesSidebarPage from "./opiniones.sidebar.page";
import TraductorSidebarPage from "./traductor.sidebar.page";

class SidebarPage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      arrOptions: [
        { id: 'portada', name: 'Portada', img: 'img/icons/portada_1.png' },
        { id: 'diseno', name: 'Diseño', img: 'img/icons/m-design.png' },
        { id: 'introduccion', name: 'Introducción', img: 'img/icons/m-introduccion.png' },
        { id: 'promo', name: 'Descripción', img: 'img/icons/m-introduccion.png' },
        { id: 'datos_contacto', name: 'Datos de contacto', img: 'img/icons/m-user.png' },
        /*{ id: 'promo', name: 'Promo', img: '' },*/
        { id: 'contacto', name: 'Contacto', img: 'img/icons/m-call.png' },
        { id: 'traductor', name: 'Traductor', img: 'img/icons/translate.svg' },
        // { id: 'documentos', name: 'Documentos', img: 'img/icons/documentos.png' },
        { id: 'carrete', name: 'Carrete', img: 'img/icons/carrete_1.png' },
        { id: 'opiniones', name: 'Opiniones', img: 'img/icons/opiniones_1.png' },
        // { id: 'galeria', name: 'Galería', img: 'img/icons/carrete_1.png' },
        { id: 'ubicacion', name: 'Ubicación', img: 'img/icons/m-place.png' },
        { id: 'redes', name: 'Redes sociales', img: 'img/icons/redes-sociales.png' },
      ],
      isOpenModal: false,
      disableHelpButton: false,
      typeModal: 0
    }
    
  }

  componentDidMount() {

  }

  selectOption(item, index) {
    this.props.initsetState({ sectionSidebar: item, })
  }

  onContactSupport(){
    const { app_id_s } = this.props.initState
    if(app_id_s==''){
      this.setState({ isOpenModal:true, typeModal: 1 })
    }else{
      this.setState({ isOpenModal:true, typeModal: 2 })
    }
  }

  sendEmailHelp(){
    const { app_id_s } = this.props.initState
    const phone = document.getElementById('input_help_phone');
    if(phone){
      if(phone.value==''){
        alert("Ingresa un número de teléfono")
      }else{
        this.setState({ disableHelpButton : true })
        let data = '';
        data = { phone : phone.value }
        this.fetchData(data)
      }
    }else {
      this.setState({ disableHelpButton : true })
      let data = '';
      data = { app_id_s : app_id_s }
      console.log("no tiene phone")
      this.fetchData(data)
    }
  }

  fetchData(data) {
    fetch(`https://tarjeta.id/editor_plus/REST/controllers/ControllerTarjeta?opt=sendEmailHelp`,{
      method: "POST",
      mode: "cors",
      body: JSON.stringify( data ),
    })
    .then(res => res.json())
    .then((res) => {
      setTimeout( () => {
        if(res.status=='ok'){
          alert('Se ha enviado una notificación a uno de nuestros asesores, en breve nos comunicaremos contigo.')
        }
        this.setState({ isOpenModal : false })
      },1000) 
    })
  }

  validatePhone(event) {
    const val = event.target.value;
    let content = [];
    Array.from(val).map(letter=>{
			if(!isNaN(letter)) {
				content.push(letter);
			}
    });
    let string = content.join("");
    event.target.value = string;
	}

  makeHeaderSub() {
    const { sectionSidebar, updateTarjeta } = this.props.initState

    return (
      <Row className={'sidebarPage__header'}>
        <Col xs={4}>
          <Row
            onClick={ () => { this.props.initsetState({ sectionSidebar: '', }) } }
            style={{ border: 0 }}
          >
            <Col xs={1}><img alt={'Imagen'} style={{width: 30, height: 30, position: 'relative', top: '7px', objectFit: 'contain', }} src={"img/icons/back.png"} /></Col>
            <Col xs={6}><p style={{ lineHeight: '45px', fontSize: '.8rem' }}>Regresar</p></Col>
          </Row>
        </Col>
        <Col xs={8}>
          <Row
            onClick={ () => { this.props.initsetState({ sectionSidebar: '', }) } }
            style={{ border: 0 }}
          >
            <Col xs={1}>
              { sectionSidebar.img !== '' ? (<img alt={'Imagen'} className={'sidebarPage__imgIcon'} src={sectionSidebar.img} />) : null }
            </Col>
            <Col>
              <p className={'sidebarPage__titleMin'} style={{ lineHeight: '45px', }}>{sectionSidebar.name}</p>
            </Col>
          </Row>
        </Col>
        {/*<Col></Col>*/}
      </Row>
    )
  }

  render() {
    const { height, viewMenu, sectionSidebar,arrCheck,updateTarjeta,arrDatos } = this.props.initState
    const { arrOptions } = this.state
    if(sectionSidebar === '') {
      return (
        <div style={{ height: `calc(${height}px - 60px)`, overflow: 'auto', background: '#f3f3f3',zIndex:'99999' }} className={`grid-cell grid-cell-contenido z-depth-1 w-menu-editor ws-menu-width ${ !viewMenu ? 'ws-menu-width-0' : '' }`}>

          <Container className={'sidebarPage__container z-depth-3'}>
          {
            
            arrOptions.map((item, index) => (
              
              <Row
                style={{ lineHeight: '60px', }}
                onClick={
                  () => { 
                    this.selectOption(item, index) 
                    this.props.initsetState({
                      refSection: item.id
                    })
                  }}
                key={`options_${index}`}>

                <Col xs={1}>
                  { item.img !== '' ? (<img alt={'Imagen'} className={'sidebarPage__imgIcon'} src={item.img} />) : null }
                </Col>

                <Col>
                {
                  ( arrCheck.hasOwnProperty('traductor') ) ?
                  <p>{item.name} { arrCheck[index].title == item.id && arrCheck[index].checkMark==true ? <span><img src={'img/icons/icon-check.svg'} style={{width:'50px',fill:'red'}}></img></span> : '' }</p>
                  :
                  <p>{item.name}</p>
                }
                </Col>
                
                {
                  (item.id == "promo" || item.id == 'carrete' || item.id == 'opiniones' || item.id == 'ubicacion') ?
                   
                  <Col xs={2} style={{textAlign:'right'}}>
                    { item.img !== '' ? 
                    (<img alt={'Imagen'} className={'sidebarPage__imgIcon__right'}  src={this.makeIconView(item)} 
                      onClick={
                        (e) => {
                          e.stopPropagation()
                          if(item.id=='promo'){
                            arrDatos.promo.checked = !arrDatos.promo.checked;
                            this.props.initsetState({arrDatos})
                          }
                          if(item.id=='carrete'){
                            arrDatos.arrCarousel.checked = !arrDatos.arrCarousel.checked;
                            this.props.initsetState({arrDatos})
                          }
                          if(item.id=='opiniones'){
                            arrDatos.arrCarouselOp.checked = !arrDatos.arrCarouselOp.checked;
                            this.props.initsetState({arrDatos})
                          }
                          if(item.id=='ubicacion'){
                            arrDatos.ubicacion.checked = !arrDatos.ubicacion.checked;
                            this.props.initsetState({arrDatos})
                          }
                        }
                      }
                    />) : 
                    null 
                    }
                  </Col>
                  : 
                  null
                }
                

              </Row>
            ))
          }

          <Row style={{ justifyContent: 'center' }}>
          {
            !updateTarjeta ? (
              <Button
                onClick={() => { this.addTarjeta(1) }}
                className={'sidebarPage__btnCreate z-depth-2 mt-5'}>
                Crear mi tarjeta.id
              </Button>
              
            ) : (
              <Button
                onClick={() => { this.addTarjeta(2) }}
                className={'sidebarPage__btnCreate z-depth-2 mt-5'}>
                Actualizar mi tarjeta.id
              </Button>
            )

          }
          <Link 
          style={{color:'#ff0350',padding:'20px',marginTop:'10px'}}
          onClick={
            () => {
              this.onContactSupport();
            }
          }
          >¿Necesitas ayuda? Da click aquí para contactar a un asesor.</Link>
          </Row>

          <Modal
            overlayClassName="Overlay__aplicaciones"
            isOpen={this.state.isOpenModal}
            onRequestClose={() => { this.setState({ isOpenModal : false}) }}
            contentLabel="Actualizar tarjeta"
            className="modal__addTarjeta"
          >
            <div className={'disenoPage__colorSugModal'} style={{textAlign:'center'}}>
              <div className={'disenoPage__colorSugModal__header'}>
                <h5 className={"col-11 text-center disenoPage__colorSugModal__title"}>Contacta a un asesor</h5>
              </div>

              <div className={'disenoPage__colorSugModal__body'}>
                { /* <img src={'img/icons/Artboard-6.png'} style={{width:'100%'}} /> */}

                    <div className={'disenoPage__colorSugModal__body__text'} >
                      <p style={{marginBottom:20}}>
                        { 
                          this.state.typeModal == 1 ? '¿Necesitas ayuda? Dejanos tu teléfono y uno de nuestros asesores te contactará a la brevedad.' : '¿Necesitas ayuda? Solo da click en el botón de abajo para notificar a uno de nuestros asesores y en breve nos comunicaremos contigo.' 
                        }
                      </p>
                      <Row>
                        <Col style={{marginBottom:0}}>
                         {
                           this.state.typeModal == 1 ? <input type={'text'} id={'input_help_phone'} className="form-control" placeholder={'Ingresa un número de teléfono'} onChange={ (event) => { this.validatePhone( event ) } }/> : null 
                         } 
                        </Col>
                      </Row>
                      <button 
                      style={{marginTop:10}} 
                      className="btn btn-primary btn-block ws_finish_button" 
                      onClick={() => { 
                        this.sendEmailHelp();
                      }}
                      disabled={this.state.disableHelpButton}
                      >
                        { this.state.typeModal==1 ? 'Enviar' : 'Enviar notificación'}
                      </button>
                    </div>

              </div>
            </div>
          </Modal>

          </Container>

        </div>
      );
    } else {
      return (
        <div style={{ height: `calc(${height}px - 60px)`, overflow: 'auto', background: '#f3f3f3' }} className={`grid-cell grid-cell-contenido z-depth-1 w-menu-editor ws-menu-width ${ !viewMenu ? 'ws-menu-width-0' : '' }`}>
          <Container className={'sidebarPage__container z-depth-3'} style={{ padding: 0, }}>
            { this.makeHeaderSub() }
            { sectionSidebar.id === 'diseno' ? <DisenoSidebarPage initState={ this.props.initState } initsetState={ (param) => this.props.initsetState(param) } /> : null }
            { sectionSidebar.id === 'datos_contacto' ? <DatosContactoSidebarPage initState={ this.props.initState } initsetState={ (param) => this.props.initsetState(param) } /> : null }
            { sectionSidebar.id === 'portada' ? <PortadaSidebarPage initState={ this.props.initState } initsetState={ (param) => this.props.initsetState(param) } /> : null }
            { sectionSidebar.id === 'introduccion' ? <IntroduccionSidebarPage initState={ this.props.initState } initsetState={ (param) => this.props.initsetState(param) } /> : null }
            { sectionSidebar.id === 'promo' ? <DescripcionSidebarPage initState={ this.props.initState } initsetState={ (param) => this.props.initsetState(param) } /> : null }
            { sectionSidebar.id === 'contacto' ? <ContactoSidebarPage initState={ this.props.initState } initsetState={ (param) => this.props.initsetState(param) } /> : null }
            { sectionSidebar.id === 'traductor' ? <TraductorSidebarPage initState={ this.props.initState } initsetState={ (param) => this.props.initsetState(param) } /> : null }
            { sectionSidebar.id === 'carrete' ? <CarreteSidebarPage initState={ this.props.initState } initsetState={ (param) => this.props.initsetState(param) } /> : null }
            { sectionSidebar.id === 'documentos' ? <DocumentosSidebarPage initState={ this.props.initState } initsetState={ (param) => this.props.initsetState(param) } /> : null }
            { sectionSidebar.id === 'opiniones' ? <OpinionesSidebarPage initState={ this.props.initState } initsetState={ (param) => this.props.initsetState(param) } /> : null }
            { sectionSidebar.id === 'galeria' ? <CarreteSidebarPage initState={ this.props.initState } initsetState={ (param) => this.props.initsetState(param) } /> : null }
            { sectionSidebar.id === 'ubicacion' ? <UbicacionSidebarPage initState={ this.props.initState } initsetState={ (param) => this.props.initsetState(param) } /> : null }
            { sectionSidebar.id === 'redes' ? <RedesSidebarPage initState={ this.props.initState } initsetState={ (param) => this.props.initsetState(param) } /> : null }
          </Container>
        </div>
      )
    }
  }

  makeIconView(item){
    const { arrDatos } =  this.props.initState;
    if(item.id=='promo'){
      return (arrDatos.promo.checked) ? "img/icons/visible.png" : "img/icons/no_visible.png" ;
    }else if(item.id=='carrete'){
      return (arrDatos.arrCarousel.checked) ? "img/icons/visible.png" : "img/icons/no_visible.png" ;
    }else if(item.id=='opiniones'){
      return (arrDatos.arrCarouselOp.checked) ? "img/icons/visible.png" : "img/icons/no_visible.png" ;
    }else if(item.id=='ubicacion'){
      return (arrDatos.ubicacion.checked) ? "img/icons/visible.png" : "img/icons/no_visible.png" ;
    }else{
      return "img/icons/visible.png"
    }
  }

  addTarjeta(opt) {
    if(opt === 1) {
      this.initsetState({ isOpenModalRegisterTarjeta: true, })
    } else if(opt === 2) {
      this.initsetState({ isOpenModalUpdateTarjeta: true, })
      this.props.updateTarjeta()
    }
  }

  initsetState(param) {
    this.props.initsetState(param)
    return true
  }

};

export default withRouter(SidebarPage)












