import axios from 'axios'
import React from 'react'
import '../../css/Components/createarticle.css'
import plusIcon from '@iconify/icons-fa-solid/plus';
import { Icon} from '@iconify/react';
import CreateCategory from './CreateCategory';
import Tooltip from '@material-ui/core/Tooltip';
import Zoom from '@material-ui/core/Zoom';

class CreateArticle extends React.Component {

    constructor(){
        super()
        this.state = {
            name: '',
            description:'',
            quantity : '',
            price : '',
            code : '',
            image: '',
            category_id:'',
            errors : [],
            categories : [],
            categoryName:'',
            onNewCategory:false,
            alreadyDone:false
        }
    }

    componentDidMount() {
        axios.get('https://etud.insa-toulouse.fr/~proximo/v2/api/categories')
            .then(res => {
                this.setState({categories : res.data}, () => {
                    console.log(this.state.categories)
                    this.setState({categoryName:res.data[0].name})
                })
            })
            .catch(error => {
                console.log(error.response)
            })
    }

    handleNameChange  = event => {
        this.setState({name : event.target.value},() => {
            console.log(this.state.name)
        })
    }
    handleCategoryChange  = event => {
        this.setState({category_id : event.target.value},() => {
            console.log(this.state.category_id);
        })
    }
    handleDescriptionChange  = event => {
        this.setState({description : event.target.value},() => {
            console.log(this.state.description)
        })
    }
    handleQuantityChange  = event => {
        this.setState({quantity : event.target.value},() => {
            console.log(this.state.quantity)
        })
    }
    handlePriceChange  = event => {
        this.setState({price : event.target.value},() => {
            console.log(this.state.price)
        })
    }
    handleCodeChange  = event => {
        this.setState({code : event.target.value},() => {
            console.log(this.state.code)
        })
    }
    handleImageChange  = event => {
        this.setState({image : event.target.files[0]},() => {
            console.log(this.state.image)
        })
    }
    handleSubmit = event => {
        event.preventDefault()

        let bodyFormData = new FormData()
        bodyFormData.set('name',this.state.name)
        bodyFormData.set('description',this.state.description)
        bodyFormData.set('quantity',this.state.quantity)
        bodyFormData.set('price',this.state.price)
        bodyFormData.set('code',this.state.code)
        bodyFormData.set('image',this.state.image)
        bodyFormData.set('category_id',this.state.category_id)
        axios.post('https://etud.insa-toulouse.fr/~proximo/v2/api/articles/store',bodyFormData)
            .then(res => {
                console.log(res)
                window.location.reload()
                this.props.handleCloseAbove();
            })
            .catch(error => {
                if(error.response.status === 401){
                    this.setState({errors : error.response.data.errors})
                }
                console.log(error.response.data.errors)
            });
    }

    handleNewCategory = () => {
        this.setState({onNewCategory:true})
    }

    handleCloseNewCategory = () => {
        this.setState({onNewCategory:false})
    }

    reload = () => {
        if (!this.state.alreadyDone){
        axios.get('https://etud.insa-toulouse.fr/~proximo/v2/api/categories')
            .then(res => {
                this.setState({categories : res.data}, () => {
                    console.log(this.state.categories)
                    this.setState({categoryName:res.data[0].name})
                    this.setState({alreadyDone:true})
                })
            })
            .catch(error => {
                console.log(error.response)
            })
        }
    }


    render(){
        if (this.state.onNewCategory){
            return <CreateCategory reload={false} handleCloseAbove={this.handleCloseNewCategory}/>
        } else {
        return(
        <div id="transp">
            <div id="formBody">
                <div id="formHead">
                    <div id="formHeadTxt">Nouvel Article</div>
                    <div id="crossClose" onClick={this.props.handleCloseAbove}>
                    <Icon icon={plusIcon} style={{transform : 'rotate(-45deg)', color: '#ffffff', fontSize: '3vw'}} />
                    </div>
                </div>
                <div id="formMainContent">
                    <form method='POST' onSubmit={this.handleSubmit}>
                        <div id="nameandcatBox">
                            <div id="nameBlock">
                                <div id="nameBlockInput">
                                    <label htmlFor='nameBox'>Nom</label>
                                    <input id="nameBox" onChange={this.handleNameChange} type='text'/>
                                </div>
                                <div id="errorNameBlock">
                                    <p id="errorName">{!this.state.name && this.state.errors.name}</p>
                                </div>
                            </div>
                            <div id="categoryBlock">
                                <div id="categoryAndAddBlock">
                                    <div id="categoryBlockInput">
                                        <label htmlFor='categoryBox'>Categorie</label>
                                        <select onClick={this.reload} id='categoryBox' onChange={this.handleCategoryChange}  defaultValue={this.state.categoryName}>
                                                <option value="Aucune">Aucune</option>
                                            {this.state.categories.map((categorie) => 
                                                <option key={categorie.id} value={categorie.id}>{categorie.name}</option>    
                                            )}
                                        </select>
                                    </div>
                                    {/* Affichage de l'icone correspondant à la catégorie
                                    <div id="littleIcon">
                                        eslint-disable-next-line
                                        {this.state.categories.map((categorie)=>
                                            {if (this.state.category_id === categorie.id){
                                                return <img id="littleIconImg" src={`https://etud.insa-toulouse.fr/~proximo/v2/storage/icon/${categorie.icon}`} alt='bonjour'/>
                                            }}
                                        )}
                                    </div> */}
                                    <div id="addCategoryBlock">
                                        <Tooltip title="Ajouter une catégorie" TransitionComponent={Zoom} aria-label="Ajouter une catégorie">
                                        <div id="addCategoryBox" onClick={this.handleNewCategory}>
                                            <Icon icon={plusIcon} style={{ color: '#ffffff', fontSize: '2vw'}} />
                                        </div>
                                        </Tooltip>
                                    </div>
                            </div>
                                <div id="errorCategoryBlock">
                                    <p id="errorCategory">{!this.state.category_id && this.state.errors.category_id}</p>
                                </div>
                            </div>
                        </div>
                        <div id="descriptionBlock">
                            <div id="descriptionBlockInput">
                                <label htmlFor='descriptionBox'>Description</label>
                                <textarea rows="5" id="descriptionBox" onChange={this.handleDescriptionChange} type='textarea'/>
                            </div>
                            <div id="errorDescriptionBlock">
                                <p id="errorDescription">{!this.state.description && this.state.errors.description}</p>
                            </div>
                        </div>
                        <div id="quantandpriBox">
                            <div id="quantityBlock">
                                <div id="quantityBlockInput">
                                    <label htmlFor='quantityBox'>Quantité</label>
                                    <input id="quantityBox" onChange={this.handleQuantityChange} type='number' min='0' step='1'/>
                                </div>
                                <div id="errorQuantityBlock">
                                    <p id="errorQuantity">{!this.state.quantity && this.state.errors.quantity}</p>
                                </div>
                            </div>
                            <div id="priceBlock">
                                <div id="priceBlockInput">
                                    <label htmlFor='priceBox'>Prix</label>
                                    <input id="priceBox" onChange={this.handlePriceChange} type='number' min='0' step='0.01'/>
                                </div>
                                <div id="errorPriceBlock">
                                    <p id="errorPrice">{!this.state.price && this.state.errors.price}</p>
                                </div>
                            </div>
                        </div>
                        <div id="codeBlock">
                            <div id="codeBlockInput">
                                <label htmlFor='codeBox'>Code</label>
                                <input id='codeBox' onChange={this.handleCodeChange} type='text'/>
                            </div>
                            <div id="errorCodeBlock">
                                <p id="errorCode">{!this.state.code && this.state.errors.code}</p>  
                            </div>
                        </div>
                        <div id="imageBlock">
                            <div id="imageBlockInput">        
                                <Tooltip style={{'text-align':'center'}} title="Télécharger la bonne image, si besoin, enelever le contour avec removebg.com et enregistrer la photo dans le dossier Images" TransitionComponent={Zoom} aria-label="Aller sur www.flaticon.com" interactive>
                                <label htmlFor="imageBox" id="customImageBox">Télécharger une Image</label>
                                </Tooltip>
                                <input id="imageBox" onChange={this.handleImageChange} type='file'/>
                            </div>
                            <div id="errorImageBlock">
                                {!this.state.image.name ?
                                <p id="errorImage">{this.state.errors.image}</p>
                                : <p id="imageName">{this.state.image.name}</p>}
                            </div>
                        </div>
                            <button id="button" type='submit'>Ajouter</button>
                    </form>
                </div>
            </div>
        </div>
        )}
    }

}

export default CreateArticle