import React, { Component } from "react"
import "./pages/general/App.css"

import { BrowserRouter as Router, Route, } from "react-router-dom"
import axios from 'axios';

import HeaderPage   from "./pages/general/header.page"
import PreviewPage  from "./pages/previewPage/preview.page"

import SidebarPage  from "./pages/sidebarPage/sidebar.page"
import 'bootstrap/dist/css/bootstrap.min.css'

import { ModalReferred } from "./componentes/Components";


class App extends Component {
  constructor(props) {
    super(props);
    this.updateWindowDimensions = this.updateWindowDimensions.bind(this);

    this.state = {
      username: '',
      isOpenModalRegisterTarjeta: false,
      formValidate: {
        isvalidate: false,
        input: ""
      },
      viewMenu: true,
      primaryColor: '#ff0350',
      secundaryColor: '#606060',
      checkedSecundaryColor: true,
      checkedTextColor: true,
      width: 0,
      height: 0,
      // sectionSidebar: { id: 'portada', name: 'Portada', img: 'img/icons/portada_1.png' },
      sectionSidebar: '',
      showRemoveButton: ['none','none','none'],

      //CheckMark
      arrCheck: [
        { title: 'portada', checkMark: true },
        { title: 'diseno', checkMark: true },
        { title: 'introduccion', checkMark: false },
        { title: 'promo', checkMark: false },
        { title: 'datos_contacto', checkMark: false },
        { title: 'contacto', checkMark: false },
        { title: 'carrete', checkMark: false },
        { title: 'documentos', checkMark: false },
        { title: 'opiniones', checkMark: false },
        // { title: 'galeria', checkMark: false},
        { title: 'ubicacion', checkMark: false },
        { title: 'redes', checkMark: false},
        { title: 'traductor', checkMark: false },
      ],

      //Values from section
      arrDatos: {
        diseno: {
          checked: true,
          coverPage: 1,
          perfil: 'img/icons/profile-demo2.png',
          portada : '',
          logo: ''
        },
        descripcion: {
          checked: true,
          nombre: '',
          cargo: '',
          empresa: '',
          slogan: '',
        },
        promo: {
          checked: true,
          titulo: '',
          descripcion: '',
          video: '',
        },
        addContact: {
          checked: true,
          titulo: '¡Agrégame a tus contactos!',
          N: "",
          TEL: "",
          URL: "",
          EMAIL: "",
          ADR_intl: "",
          ADR_work: "",
          ADR_postal: "",
          ADR_parcel: ""
        },
        email: {
          checked: true,
          email: [],
          icon: "mail",
          titulo: "¡Escríbeme un correo!",
        },
        telefono: {
          checked: true,
          telefono: [],
          icon: "mail",
          titulo: "¡Llámame!",
        },
        whatsapp: {
          checked: true,
          whatsapp: [],
          icon: "mail",
          titulo: "¡Mándame un whats!",
        },
        ubicacion: {
          checked: true,
          direccion: '',
          ciudad: '',
          codigoPostal: '',
          estado: ''
        },
        facebook: {
          checked: false,
          icon: 'facebook',
          url: '',
          img: ''
        },
        instagram: {
          checked: false,
          icon: 'instagram',
          url: '',
          img: ''
        },
        linkedin: {
          checked: false,
          icon: 'linkedin',
          url: '',
          img: ''
        },
        youtube: {
          checked: false,
          icon: 'youtube',
          url: '',
          img: ''
        },
        twitter: {
          checked: false,
          icon: 'twitter',
          url: '',
          img: ''
        },
        site: {
          checked: false,
          icon: 'site',
          url: '',
          img: ''
        },
        arrCarousel: {
          title: '',
          checked: true,
          arrImages: [
          ],
        },
        arrDocumentos: {
          title: 'Mi nube de documentos',
          checked: true,
          arrFiles: [
          ],
        },
        arrCarouselOp: {
          title: "",
          checked: true,
          arrOpiniones: [
          ]
        },
        zoom: {
          view: false,
          checked: false,
          icon: 'zoom',
          url: '',
          img: ''
        },
        behance: {
          view: false,
          checked: false,
          icon: 'behance',
          url: '',
          img: ''
        },
        blog: {
          view: false,
          checked: false,
          icon: 'blog',
          url: '',
          img: ''
        },
        deviantart: {
          view: false,
          checked: false,
          icon: 'deviantart',
          url: '',
          img: ''
        },
        discord: {
          view: false,
          checked: false,
          icon: 'discord',
          url: '',
          img: ''
        },
        dribble: {
          view: false,
          checked: false,
          icon: 'dribble',
          url: '',
          img: ''
        },
        drive: {
          view: false,
          checked: false,
          icon: 'drive',
          url: '',
          img: ''
        },
        dropbox: {
          view: false,
          checked: false,
          icon: 'dropbox',
          url: '',
          img: ''
        },
        feed: {
          view: false,
          checked: false,
          icon: 'feed',
          url: '',
          img: ''
        },
        flickr: {
          view: false,
          checked: false,
          icon: 'flickr',
          url: '',
          img: ''
        },
        foursquare: {
          view: false,
          checked: false,
          icon: 'foursquare',
          url: '',
          img: ''
        },
        github: {
          view: false,
          checked: false,
          icon: 'github',
          url: '',
          img: ''
        },
        hangout: {
          view: false,
          checked: false,
          icon: 'hangout',
          url: '',
          img: ''
        },
        tarjetaid: {
          view: false,
          checked: false,
          icon: 'tarjetaid',
          url: '',
          img: ''
        },
        kickstart: {
          view: false,
          checked: false,
          icon: 'kickstart',
          url: '',
          img: ''
        },
        messenger: {
          view: false,
          checked: false,
          icon: 'messenger',
          url: '',
          img: ''
        },
        photos: {
          view: false,
          checked: false,
          icon: 'photos',
          url: '',
          img: ''
        },
        pinterest: {
          view: false,
          checked: false,
          icon: 'pinterest',
          url: '',
          img: ''
        },
        reddit: {
          view: false,
          checked: false,
          icon: 'reddit',
          url: '',
          img: ''
        },
        snapchat: {
          view: false,
          checked: false,
          icon: 'snapchat',
          url: '',
          img: ''
        },
        soundcloud: {
          view: false,
          checked: false,
          icon: 'soundcloud',
          url: '',
          img: ''
        },
        spotify: {
          view: false,
          checked: false,
          icon: 'spotify',
          url: '',
          img: ''
        },
        tiktok: {
          view: false,
          checked: false,
          icon: 'tiktok',
          url: '',
          img: ''
        },
        tumblr: {
          view: false,
          checked: false,
          icon: 'tumblr',
          url: '',
          img: ''
        },
        twitch: {
          view: false,
          checked: false,
          icon: 'twitch',
          url: '',
          img: ''
        },
        vimeo: {
          view: false,
          checked: false,
          icon: 'vimeo',
          url: '',
          img: ''
        },
      },
      textUpload: '',
      updateTarjeta: false,
      app_id_s: '',
      refSection : '',
      id_tarjeta_principal: '',
      id_pretarjeta: '',
      id_lead: '',
      showSocialNetworks: false,
      arrRedesSociales:[],
      iconVersion: 'v1',
      translate: false,
    }
  }

  
  componentDidMount() {

    this.updateWindowDimensions();
    window.addEventListener('resize', this.updateWindowDimensions);

    let param = window.location.search;

    if( param.indexOf('?app_id_s=') !== -1 ) {
      let app_id_s = param.split('?app_id_s=')
      app_id_s = app_id_s[1]
      const regex = /#/gi
      app_id_s = app_id_s.replaceAll(regex, '')

      fetch(`https://tarjeta.id/editor_plus/REST/controllers/ControllerTarjeta?opt=getConstructorEditorPlus`, {
        method: "POST",
        mode: "cors",
        body: JSON.stringify( { app_id_s }),
      }).then(res => res.json()).then((res) => {

        this.setState({ app_id_s, })
        if(res.state) {
          if(res.status === 0) {
            window.location = `https://tarjeta.id/payments.php?nombre=${res.nombre}&telefono=${res.telefono}&correo=${res.correo}&modalidad=plus&id=${app_id_s}`
          } else {
            //Construyendo tarjeta
            this.__construnctorTarjeta(res, app_id_s)
          }
        } else {
          let { arrDatos } = this.state
          arrDatos.descripcion.nombre = res.nombre
          this.setState({ app_id_s, arrDatos, })
        }
      })

    }

    if(this._GET('id_tarjeta_principal')!=''){
      const id_tarjeta_principal = this._GET('id_tarjeta_principal');
      this.setState({id_tarjeta_principal})
    }

    if(this._GET('id_pretarjeta')!=''){
      const id_pretarjeta = this._GET('id_pretarjeta');
      this.setState({id_pretarjeta})
    }

    if(this._GET('id_lead')!=''){
      const id_lead = this._GET('id_lead');
      this.setState({id_lead})
    }

  }

  _GET(variable) {
    let query = window.location.search.substring(1);
    let vars = query.split('&');
    for (let i = 0; i < vars.length; i++) {
      let pair = vars[i].split('=');
      if (decodeURIComponent(pair[0]) == variable) {
        return decodeURIComponent(pair[1]);
      }
    }
    return '';
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.updateWindowDimensions);
  }

  updateWindowDimensions() {
    this.setState({ width: window.innerWidth, height: window.innerHeight });
  }

  updateState(obj){
    this.setState(obj)
  }

  render() {
    return (
      <div style={{ background: '#f2f2f2', height: '100%', paddingTop: 60 }}>
        <Router>
          {/* Header */}
          <HeaderPage initState={ this.state } initsetState={ (param) => this.setState(param) } />

          {/* Sections */}
          <Route exact path="/">
            <PreviewPage
              addTarjeta={() => { this.addTarjeta() }}
              initState={ this.state } initsetState={ (param) => this.setState(param)}
            />
            <SidebarPage
              addTarjeta={() => { this.addTarjeta() }}
              updateTarjeta={() => { this.updateTarjeta() }}
              initState={ this.state } initsetState={ (param) => this.setState(param)}
            />
            <ModalReferred state={this.state} updateState={this.updateState.bind(this)} get={this._GET.bind(this)} />
          </Route>

          {/* Tabs */}
          {/*<FooterPage initState={ this.state } initsetState={ (param) => this.setState(param) } />*/}
        </Router>
      </div>
    );
  }

  __construnctorTarjeta(data, app_id_s) {
    let { app_id, state } = data
    //Ocultamos el modal de registro
    state.updateTarjeta = true
    state.textUpload = ''
    state.isOpenModalRegisterTarjeta = false

    delete state.height
    delete state.app_id_s
    delete state.width
    
    //Agregamos las rutas de imagen
    state.arrDatos.diseno.portada = state.arrDatos.diseno.portada !== '' ? `https://tarjeta.id/imports/${app_id}/imgs/IMG-PORTADA-ORIGINAL.png?v=asf` : ''
    state.arrDatos.diseno.logo = state.arrDatos.diseno.logo !== '' ? `https://tarjeta.id/imports/${app_id}/imgs/IMG-LOGO-ORIGINAL.png?v=asf` : ''
    state.arrDatos.diseno.perfil = state.arrDatos.diseno.perfil !== '' ? `https://tarjeta.id/imports/${app_id}/imgs/IMG-PERFIL-ORIGINAL.png?v=asf` : 'img/icons/profile-demo2.png'



    let { arrDocumentos } = state.arrDatos
    if(!arrDocumentos) {
      arrDocumentos = {
        arrFiles: [],
        checked: false,
        title: "Mi nube de documentos",
      }
      state.arrDatos.arrDocumentos = arrDocumentos
    }
    this.setState({...state})
  }

  addTarjeta() {
    const { arrDatos, } = this.state
    const { email,descripcion,telefono } = arrDatos
    const regex = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
    const nombre = descripcion.nombre.trim();

    if(nombre.length<1){
      alert("Debes ingresar un nombre a tu tarjeta.id")
      this.setState({
        formValidate:{
          isValidate: true,
          input: "nombre"
        },
        sectionSidebar:{ 
          id: 'introduccion', 
          name: 'Introducción', 
          img: 'img/icons/descripciขn.png' 
        },
        isOpenModalRegisterTarjeta: false
      });
      return false
    }else{
      this.setState({
        formValidate:{
          isValidate: false,
          input: ""
        },
      })
    }

    if(telefono.telefono.length==0){
      alert("Ingresa un número de teléfono");
      this.setState({
        formValidate:{
          isValidate: true,
          input: "telefono"
        },
        sectionSidebar:{ 
          id: 'datos_contacto', 
          name: 'Datos de contacto', 
          img: 'img/icons/m-user.png' 
        },
        isOpenModalRegisterTarjeta: false
      });
      return false;
    }else{
      this.setState({
        formValidate:{
          isValidate: false,
          input: ""
        },
      })
    }
    
    if(email.email.length==0){
      alert("Ingresa un correo electrónico");
      this.setState({
        formValidate:{
          isValidate: true,
          input: "email"
        },
        sectionSidebar:{ 
          id: 'datos_contacto', 
          name: 'Datos de contacto', 
          img: 'img/icons/m-user.png' 
        },
        isOpenModalRegisterTarjeta: false
      });
      return false;
    }else{
      this.setState({
        formValidate:{
          isValidate: false,
          input: ""
        },
      })
    }

    if(!regex.test(email.email[0].email)){
      alert("Debes agregar un correo electrónico valido");
      this.setState({
        formValidate:{
          isValidate: true,
          input: "email"
        },
        sectionSidebar:{ 
          id: 'datos_contacto', 
          name: 'Datos de contacto', 
          img: 'img/icons/m-user.png' 
        },
        isOpenModalRegisterTarjeta: false
      });
      return false;
    }else{
      this.setState({
        formValidate:{
          isValidate: false,
          input: ""
        },
      })
    }

    if (/[^a-z0-9]/g.test(this.state.username)) {
      alert('Error, por favor ingresa un nombre de usuario sin caracteres especiales.')
      return false
    }

    fetch(`https://tarjeta.id/editor_plus/REST/controllers/ControllerTarjeta?opt=existTarjeta`, {
      method: "POST",
      mode: "cors",
      body: JSON.stringify( this.state ),
    })
    .then(res => res.json())
    .then((res) => {

      if(res.exist === 1) {
        if (res.existUser != 0) {
					alert("El nombre de la tarjeta no se encuentra disponible, intenta con otro.")
				}
				if (res.existEmail != 0) {
					alert("El correo que proporcionaste ya fue utilizado, intenta con otro.")
				}
      } else if (res.exist === 0) {
        fetch(`https://tarjeta.id/editor_plus/REST/controllers/ControllerTarjeta?opt=addTarjeta`, {
          method: "POST",
          mode: "cors",
          body: JSON.stringify( this.state ),
        })
        .then(res0 => res0.json())
        .then((res0) => {
          //Redireccionar
          const { app_id_secret, } = res0
          // const app_id_secret = 'oUfbo8qpd-kzx09w5zQ-5NiV5Gz8mu-EQJ9DY'

          this.setState({ textUpload: 'Subiendo fotografía de perfil...', })
          this.promiseUploadProfiles('perfil', arrDatos.diseno.files_perfil, app_id_secret).then((a) => {

            this.setState({ textUpload: 'Subiendo logo...', })
            this.promiseUploadProfiles('logo', arrDatos.diseno.files_logo, app_id_secret).then((b) => {

              this.setState({ textUpload: 'Subiendo portada...', })
              this.promiseUploadProfiles('portada', arrDatos.diseno.files_portada, app_id_secret).then((c) => {

                this.setState({ textUpload: `Subiendo carrusel de imágenes...`, })
                this.promiseUploadSlider(app_id_secret).then((d) => {

                  this.promiseUploadTestimoniales(app_id_secret).then((d) => {

                    this.setState({ textUpload: '', })
                    alert('¡Tarjeta registrada con éxito!')
                    this.setState({ isOpenModalRegisterTarjeta: false, })
                    console.log('tarjeta registrada')
                    // window.location = `https://tarjeta.id/payments.php?nombre=${res0.user}&telefono=${res0.phone}&correo=${res0.email}&modalidad=plus&id=${app_id_secret}`
                    // window.location = `https://tarjeta.id/${this.state.username}`
                  })
                })
              })
            })
          })
        })
      }
    })
  }

  updateTarjeta() {
    const { arrDatos, app_id_s } = this.state

    fetch(`https://tarjeta.id/editor_plus/REST/controllers/ControllerTarjeta?opt=updateTarjeta`, {
      method: "POST",
      mode: "cors",
      body: JSON.stringify( {
        ...this.state,
      } ),
    })
    .then(res0 => res0.json())
    .then((res0) => {
      //Redireccionar

      this.setState({ textUpload: 'Subiendo fotografía de perfil...', })
      this.promiseUploadProfiles('perfil', arrDatos.diseno.files_perfil, app_id_s).then((a) => {

        this.setState({ textUpload: 'Subiendo logo...', })
        this.promiseUploadProfiles('logo', arrDatos.diseno.files_logo, app_id_s).then((b) => {

          this.setState({ textUpload: 'Subiendo portada...', })
          this.promiseUploadProfiles('portada', arrDatos.diseno.files_portada, app_id_s).then((c) => {

            this.setState({ textUpload: `Subiendo carrusel de imágenes...`, })
            this.promiseUploadSlider(app_id_s).then((d) => {

              this.promiseUploadTestimoniales(app_id_s).then((d) => {

                this.setState({ textUpload: '', })
                alert('¡Tarjeta actualizada con éxito!')
                this.setState({ isOpenModalRegisterTarjeta: false, })
                window.location = `https://tarjeta.id/${this.state.username}`
              })
            })
          })
        })
      })
    })
  }

  promiseUploadProfiles(opt, file, app_id_secret) {
    let { arrDatos, } = this.state
    
    return new Promise((resolve, reject) => {

      if(file) {
        let formData = new FormData()
        formData.append('file', file)
        formData.append('post', opt)
        axios.post(`https://tarjeta.id/editor_plus/REST/controllers/ControllerUploads?opt=uploadImgPortada&tipo=${opt}&app_id_secret=${app_id_secret}`, formData, {})
        .then(res => {
          if(opt === 'perfil')
            arrDatos.diseno.files_perfil = null
          else if(opt === 'portada')
            arrDatos.diseno.files_portada = null
          else if(opt === 'logo')
            arrDatos.diseno.files_logo = null
          this.setState({ arrDatos })
          resolve('ok')
        })

      } else {
        resolve('ok')
      }

    })
  }

  promiseUploadSlider(app_id_secret) {
    return new Promise((resolve, reject) => {
      const { arrDatos, } = this.state
      const { arrCarousel } = arrDatos
      const { arrImages } = arrCarousel

      let formData = new FormData()
      let flagUpload = false

      if(arrImages.length === 0) {
        resolve('ok')
      }

      for(var a in arrImages) {
        if(arrImages[a].files!='') {
          flagUpload = true
          formData.append('files[]', arrImages[a].files)
          formData.append('post[]', a)
        }

        if(a == (arrImages.length - 1)) {
          if(flagUpload) {
            
            axios.post(`https://tarjeta.id/editor_plus/REST/controllers/ControllerUploads?opt=uploadImgCarouselIDPlus&app_id_secret=${app_id_secret}`, formData, {})
            .then(res => {
              for(var a in arrImages) {
                if(arrImages[a].files) {
                  arrImages[a].files = null
                }

                if(a == (arrImages.length - 1)) {
                  this.setState({ arrDatos })
                  resolve('ok')
                }
              }
            })
          } else {
            resolve('ok')
          }
        }
      }
    })
  }

  promiseUploadTestimoniales(app_id_secret) {
    return new Promise((resolve, reject) => {
      const { arrDatos, } = this.state
      const { arrCarouselOp } = arrDatos
      const { arrOpiniones } = arrCarouselOp

      let formData = new FormData()
      let flagUpload = false

      if(arrOpiniones.length === 0) {
        resolve('ok')
      }

      for(var a in arrOpiniones) {
        if(arrOpiniones[a].files!='') {
          flagUpload = true
          formData.append('files[]', arrOpiniones[a].files)
          formData.append('post[]', a)
        }

        if(a == (arrOpiniones.length - 1)) {
          if(flagUpload) {
            axios.post(`https://tarjeta.id/editor_plus/REST/controllers/ControllerUploads?opt=uploadImgCarouselOpinionesIDPlus&app_id_secret=${app_id_secret}`, formData, {})
            .then(res => {
              for(var a in arrOpiniones) {
                if(arrOpiniones[a].files) {
                  arrOpiniones[a].files = null
                }

                if(a == (arrOpiniones.length - 1)) {
                  this.setState({ arrDatos })
                  resolve('ok')
                }
              }
            })
          } else {
            resolve('ok')
          }
        }
      }
    })
  }


}

export default App;







