import React from 'react';
import * as Yup from 'yup';
import { Formik, Field, Form } from 'formik';
import { Row, Col, Modal, Button} from 'react-bootstrap'

import NotFound from '../../Images/not_found.png';
const SUPPORTED_FORMATS = ["image/jpg", "image/jpeg", "image/gif", "image/png"];

const NewPlazaSchema = Yup.object().shape({
    nombre : Yup.string().required('El nombre es requerido').min(5).max(20),
    description : Yup.string().required('La description es requerida').min(5).max(20),
    salario : Yup.number().required('El salario es requerido'),
    imagen:  Yup.mixed().required('El imagen es requerido').test('fileSize', "El archivo es demasiado grande", value => {
        if(!value || value.length <= 0) return false
        return value[0].size < 200000
    }).test('fileType', "El tipo del archivo no es válido", value => {
        if(!value) return false
        return SUPPORTED_FORMATS.includes(value[0].type)
    })
})

export default function Manual ( props ) {

    let [ filename, setFilename ] = React.useState('');
    let [ file, setFile ] = React.useState(undefined);
    let [ type, setType ] = React.useState(undefined);
    let [ validType, setValidType ] = React.useState(false);

    let { visible, onClose } = props
    const hiddenFileInput = React.useRef(null);

    const PickFile = event => hiddenFileInput.current.click();

    React.useEffect(() => {
        if( SUPPORTED_FORMATS.includes(type) ){
            setValidType(true)
        }else{
            setValidType(false)
        }

    }, [type])


    return (
        <Modal size="lg" aria-labelledby="contained-modal-title-vcenter" centered  show={visible} onHide={onClose}>
            <Modal.Header>
                <button onClick={onClose}  type="button" className="close" data-dismiss="modal">&times;</button>
                <h4 className="modal-title">Agregar plaza</h4>
            </Modal.Header>
            <Modal.Body className="modal-body">

                <Formik

                    initialValues={{
                        nombre: '',
                        description: '',
                        salario: '',
                        imagen: '',
                    }}

                    validationSchema={NewPlazaSchema}
                    onSubmit={ (values) => {
                        // console.log('VALUES >> ',values)
                        props.setManual(false)
                    }} >


                    { ({  errors, touched, validateField, validateForm, setFieldValue  }) => (
                        <Form>
                            <Row>

                                <Col md="4">
                                    <div className="img-container">
                                        <img alt="agregar plaza manual" src={ validType ? file : NotFound}/>
                                    </div>
                                </Col>

                                <Col md="8">

                                    <input 
                                        value={filename} 
                                        type="text" 
                                        className="file-upload-input" 
                                        disabled="" 
                                        placeholder="Ningún archivo seleccionado" readOnly
                                    />

                                    <Button className="btn_add_producto_confirm" style={{ marginLeft : 15 }} onClick={PickFile}>
                                        SUBIR FOTO
                                    </Button>

                                    {errors.imagen && touched.imagen && <div className="error_feedback">{errors.imagen}</div>}
                                    <input
                                        multiple={false}
                                        type="file"
                                        ref={hiddenFileInput}
                                        onChange={(event) => {
                                            const files = event.target.files;
                                            console.log('files crud ', files[0])
                                            let myFiles =Array.from(files);
                                            setFieldValue("imagen", myFiles);
                                            setFilename(myFiles[0].name)
                                            setType(myFiles[0].type)
                                            const objectUrl = URL.createObjectURL(files[0])
                                            setFile(objectUrl)
                                        }}
                                        style={{display: 'none'}}
                                    />

                                </Col>

                            </Row>
                            <div className="data_product">
                                <Row>
                                    <Col md="12">

                                        {errors.nombre && touched.nombre && <div className="error_feedback">{errors.nombre}</div>}
                                        <Field name="nombre" placeholder="Nombre de la plaza"/>

                                        {errors.description && touched.description && <div className="error_feedback">{errors.description}</div>}
                                        <Field name="description">
                                            {({ field, form, meta }) => {
                                                return(
                                                    <textarea id="description" name="description" value={field.value} onChange={field.onChange} placeholder="Descripción general de la plaza"></textarea>
                                                )
                                            }}
                                        </Field>

                                        {errors.salario && touched.salario && <div className="error_feedback">{errors.salario}</div>}
                                        <Field name="salario" type="number" placeholder="Salario"/>


                                    </Col>
                                    <div className="add_producto_confirm">
                                        <button className="btn_add_producto_confirm" type="submit">Agregar plaza</button>
                                    </div>
                                </Row>
                            </div>
                        </Form>
                    )}




                </Formik>
            </Modal.Body>
        </Modal>
    )
}
