import React, { Component, } from 'react'
import { withRouter, } from 'react-router-dom'
import { Row, Col, Tooltip, OverlayTrigger, Form, } from 'react-bootstrap'
import Select from 'react-select'
import Modal from 'react-modal'
import { TwitterPicker, SketchPicker } from 'react-color';

const renderTooltipColors = (props) => (
  <Tooltip id="button-tooltip" {...props}>
    Haz click para cambiar de modo.
  </Tooltip>
);

const customStyles = {
  content : {top: '50%',left: '50%',right: 'auto',bottom: 'auto',marginRight: '-50%',transform: 'translate(-50%, -50%)',width: 'auto',height: 'auto',}
};

const customStylesSelect = {
  control: styles => ({ ...styles, backgroundColor: '#fff', width: '90%', margin: '0 auto', marginBottom: 20, }),
}

class DisenoPage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      arrColorsSug: [],
      colorSelected: '',
      isOpenSelectColor: false,
      primaryColorPicker: 1,
      secundaryColorPicker: 1
    }

    this.onSubmit      = this.onSubmit.bind(this);
    this.onAddColorSug = this.onAddColorSug.bind(this);
  }

  componentDidMount() {  }

  onSubmit() {  }

  removeImageInput(input,array) {
    let {arrDatos,showRemoveButton} = this.props.initState
    document.getElementById(input).value = ""

    if(input=="upload-file-fondo")
      arrDatos.diseno.portada = ''

    if(input=="upload-file-logo")
      arrDatos.diseno.logo = ''

    showRemoveButton[array] = 'none'
    console.log(showRemoveButton)
  }

  onFileChange(opt, file) {
    if(file.target.files.length === 0)
      return false


    let { arrDatos,showRemoveButton,arrCheck } = this.props.initState
    const imgURL = URL.createObjectURL( file.target.files[0] )

    if(opt === 'perfil') {
      arrDatos.diseno.perfil = imgURL
      arrCheck[1].checkMark = true;
      arrDatos.diseno.files_perfil = file.target.files[0]
    } else if(opt === 'logo') {
      showRemoveButton[2] = 'block';

      this.setState({ arrColorsSug: [] })
      let $this = this

      arrDatos.diseno.logo = imgURL
      arrDatos.diseno.files_logo = file.target.files[0]
      let img = document.createElement('img')
      img.setAttribute('src', imgURL )
      img.addEventListener('load', function() {
        let vibrant = new window.Vibrant(img)
        let swatches = vibrant.swatches()
        for (let swatch in swatches) {
          if (swatches.hasOwnProperty(swatch) && swatches[swatch]) {
            $this.onAddColorSug(swatches[swatch].getHex())
          }
        }
      });
    }else if(opt == 'fondo') {
      showRemoveButton[1] = 'block';
      arrDatos.diseno.portada = imgURL;
      arrDatos.diseno.files_portada = file.target.files[0]
    }

    this.initsetState({ arrDatos })
  }

  onAddColorSug(hex) {
    this.setState({ arrColorsSug: this.state.arrColorsSug.concat( hex ) })
  }

  onSelectColorSug(color, opt, selected) {
    if(opt === 1)
      this.setState({ isOpenSelectColor: true, colorSelected: color, })
    else {
      this.setState({ isOpenSelectColor: false, colorSelected: color, })
      if(selected === 1)
        this.initsetState({ primaryColor: this.state.colorSelected });
      else
        this.initsetState({ secundaryColor: this.state.colorSelected });
    }

  }

  render() {
    const { arrColorsSug, isOpenSelectColor, primaryColorPicker, secundaryColorPicker, } = this.state
    let { arrDatos, checkedSecundaryColor, checkedTextColor,showRemoveButton,primaryColor,secundaryColor } = this.props.initState

    return (
      <div style={{ padding: 15, background: '#f3f3f3', }}>
        { /* Seleccionar tema */ }

        <div style={{ display: 'none' }}>
          <Row>
            <p>Seleccionar tema <b>*</b></p>
          </Row>
          <Row>
            <Select
              onChange={(item) => this.setState({selectPlantilla: item.id})}
              placeholder={"Elige una plantilla"}
              options={[
              { id: 1, label: 'Plantilla 1', value: 'Plantilla 1', },
              { id: 2, label: 'Plantilla 2', value: 'Plantilla 2', },
              { id: 3, label: 'Plantilla 3', value: 'Plantilla 3', },
              ]}
              styles={customStylesSelect}
            />
          </Row>
        </div>
        { /* Perfil */ }

        <div>
          <form className="formPage__form" onSubmit={ this.onSubmit } style={{ marginTop: 20, clear: 'both' }}>
            
            <div key={`div_upload_perfil`}>

              {/*Imagen de perfil*/}

              <p>Fotografía de perfil <b>*</b></p>
              <img
                src={
                  arrDatos.diseno.perfil == 'img/icons/profile-demo2.png'
                  ? 'img/icons/placeholder1.png'
                  : arrDatos.diseno.perfil
                }
                alt={'Placeholder'}
                style={{ width: 100, height: 100, objectFit: 'contain' }}
              />
              <label className="form-group" htmlFor={`upload-file-fperfil`} style={{ display: 'block', margin: 0, }}>
                <p className={'btn btn-primary z-depth-2 disenoPage__btnUpload'} htmlFor={`upload-file-fperfil`} style={{ fontSize: '1rem', color: '#111', cursor: 'pointer', }}>Subir imagen</p>
                <input accept="image/png, image/jpeg" style={{ display: 'none' }} id={`upload-file-fperfil`} type="file" onChange={(file) => this.onFileChange('perfil', file)} />
              </label>
              <p style={{ fontSize: 12, color: '#777' }}>Medida recomendada 800x800px</p>

              {/*Imagen de Fondo*/}

              <p>Fondo <b>*</b></p>
              <img
                src={ arrDatos.diseno.portada === '' ? 'img/icons/placeholder1.png' : arrDatos.diseno.portada }
                alt={'Placeholder'}
                style={{ width: 100, height: 100, objectFit: 'contain' }}
              />
              <label className="form-group" htmlFor={`upload-file-fondo`} style={{ display: 'block', margin: 0, }}>
                <p className={'btn btn-primary z-depth-2 disenoPage__btnUpload'} htmlFor={`upload-file-fondo`} style={{ fontSize: '1rem', color: '#111', cursor: 'pointer', }}>Subir imagen</p><br />   

                <a href="#" className="btn z-depth-2 disenoPage__btnUpload__remove mb-3" style={{display:showRemoveButton[1]}}onClick={ _ => this.removeImageInput("upload-file-fondo",1) }>Remover imagen</a>       

                <input accept="image/png, image/jpeg" style={{ display: 'none' }} id={`upload-file-fondo`} type="file" onChange={(file) => this.onFileChange('fondo', file)} />

              </label>
              <p style={{ fontSize: 12, color: '#777' }}>Medida 1280x800px</p>

              {/* LOGO */}

              <p>Logo <b>*</b></p>
              <img
                src={arrDatos.diseno.logo === '' ? 'img/icons/placeholder3.png' : arrDatos.diseno.logo}
                alt={'Placeholder'}
                style={{ width: 100, height: 100, objectFit: 'contain' }}
              />
              <label className="form-group" htmlFor={`upload-file-logo`} style={{ display: 'block', margin: 0, }}>
                <p className={'btn btn-primary z-depth-2 disenoPage__btnUpload'} htmlFor={`upload-file-logo`} style={{ fontSize: '1rem', color: '#111', cursor: 'pointer', }}>Subir imagen</p>

                <a href="#" className="btn z-depth-2 disenoPage__btnUpload__remove mb-3" style={{display:showRemoveButton[2]}}onClick={ _ => this.removeImageInput("upload-file-logo",2) }>Remover imagen</a> 
                
                <input accept="image/png, image/jpeg" style={{ display: 'none' }} id={`upload-file-logo`} type="file" onChange={(file) => this.onFileChange('logo', file)} />
              </label>
              <p style={{ fontSize: 12, color: '#777' }}>Medida 400x40px</p>

              {
                arrColorsSug.length > 0 ? (
                  <div className={'disenoPage__colorsSug'}>
                    <h4>Colores sugeridos</h4>
                    <p>*Los siguientes colores son obtenidos de tu logo, te sugerimos que los utilices para personalizar tu tarjeta.</p>
                    <Row>
                      {arrColorsSug.map((t,e) => (
                        <Col onClick={() => { this.onSelectColorSug(t, 1) }} style={{background: t}}></Col>
                      ))}
                    </Row>
                  </div>
                ) : null
              }


            </div>

          </form>

        </div>

        <hr />
        { /* Selector de colores */ }
        <div>
          <p style={{ marginBottom: 0, }}>Color principal</p>
          <OverlayTrigger
            placement="left"
            delay={{ show: 250, hide: 400 }}
            overlay={ renderTooltipColors }
          >
            <p style={{ marginBottom: 10, fontSize: '.9rem', color: '#777', cursor: 'pointer' }} onClick={ () => { this.setState({ primaryColorPicker: primaryColorPicker === 1 ? 2 : 1 }) } }>Modo { primaryColorPicker === 1 ? 'básico' : 'profesional' }</p>
          </OverlayTrigger>
          {
            primaryColorPicker === 1 ? (
              <TwitterPicker
                color={ this.props.initState.primaryColor }
                onChangeComplete={ (color) => { this.initsetState({ primaryColor: color.hex }) } }
              />
            ) : (
              <SketchPicker
                color={ this.props.initState.primaryColor }
                onChangeComplete={ (color) => { this.initsetState({ primaryColor: color.hex }) } }
              />
            )
          }
          
          {
            checkedSecundaryColor ? (
            <>
              <p style={{ marginTop: 15, marginBottom: 0, }}>Color secundario</p>
              <OverlayTrigger
                placement="left"
                delay={{ show: 250, hide: 400 }}
                overlay={ renderTooltipColors }
              >
                <p style={{ marginBottom: 10, fontSize: '.9rem', color: '#777', cursor: 'pointer' }} onClick={ () => { this.setState({ secundaryColorPicker: secundaryColorPicker === 1 ? 2 : 1 }) } }>Modo { secundaryColorPicker === 1 ? 'básico' : 'profesional' }</p>
              </OverlayTrigger>
              {
                secundaryColorPicker === 1 ? (
                  <TwitterPicker
                    color={ this.props.initState.secundaryColor }
                    onChangeComplete={ (color) => { this.initsetState({ secundaryColor: color.hex }) } }
                  />
                ) : (
                  <SketchPicker
                    color={ this.props.initState.secundaryColor }
                    onChangeComplete={ (color) => { this.initsetState({ secundaryColor: color.hex }) } }
                  />
                )
              }
            </>
            ) : null
          }

          <div className="mb-3" style={{ marginTop: 10, }}>
            <Form.Check 
              type={'checkbox'}
              id={`available-color-secundary`}
              label={`Habilitar color secundario`}
              checked={checkedSecundaryColor}
              onChange={ 
                (event) => { 
                  secundaryColor = (checkedSecundaryColor) ? primaryColor : secundaryColor ;
                  this.initsetState({ checkedSecundaryColor: !checkedSecundaryColor, secundaryColor}) 
                }
              }
            />

          </div>
          <div className="mb-3" style={{ marginTop: 10, }}>
            <Form.Check 
              type={'checkbox'}
              id={`available-text-color`}
              label={`Habilitar color en el texto`}
              checked={checkedTextColor}
              onChange={ (event) => { this.initsetState({ checkedTextColor: !checkedTextColor }) }}
            />
          </div>

        </div>


        <Modal
          overlayClassName="Overlay__aplicaciones"
          isOpen={isOpenSelectColor}
          onRequestClose={() => { this.setState({isOpenSelectColor: false}) }}
          style={customStyles}
          contentLabel="Elegir color"
        >
          <div className={'disenoPage__colorSugModal'}>
            <h5>Aplicar en</h5>
            <hr />
            <p onClick={() => { this.onSelectColorSug('', 2, 1) }}>Color primario</p>
            <p onClick={() => { this.onSelectColorSug('', 2, 2) }}>Color secundario</p>
          </div>
        </Modal>


      </div>
    );
  }

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

};

export default withRouter(DisenoPage)












