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

class EditArticle extends React.Component {

    constructor(props){
        super(props)
        this.state = {
            name: this.props.article.name,
            description:this.props.article.desc,
            quantity : this.props.article.quantity,
            price : this.props.article.price,
            code : this.props.article.code,
            image: '',
            categories:[],
            category_id:this.props.article.category.id,
            categoryName:this.props.article.category.name,
            errors : [],
            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)
                })
            })
            .catch(error => {
                console.log(error.response)
            })
    }

    handleCategoryChange  = event => {
        this.setState({category_id : event.target.value},() => {
            console.log(this.state.category_id);
        })
    }

    handleNameChange  = event => {

        this.setState({name : event.target.value},() => {
            console.log(this.state.name)
        })
    }
    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 => {
        console.log('ok');
        this.setState({image : event.target.files[0]},() => {
            console.log(this.state.image)
        })
    }
    handleSubmit = event => {
        event.preventDefault()
        
    
        let articleUpdated = {}
        articleUpdated.name = this.state.name;
        articleUpdated.description = this.state.description;
        articleUpdated.quantity = this.state.quantity;
        articleUpdated.price = this.state.price;
        articleUpdated.code = this.state.code;
        articleUpdated.category_id = this.state.category_id;
        let formData = new FormData();
        if (this.state.image) {
            formData.set('image',this.state.image)
            axios.post(`https://etud.insa-toulouse.fr/~proximo/v2/api/articles/${this.props.article.id}`,formData)
            .then(res => {
                console.log(res)
                this.setState({errors : []})
            })
            .catch(error => {
                
                if(error.response.status === 401){
                    this.setState({errors : error.response.data.errors})
                }
                
            });
        }

        axios.put(`https://etud.insa-toulouse.fr/~proximo/v2/api/articles/${this.props.article.id}`,articleUpdated)
            .then(res => {
                console.log(res)
                this.setState({errors : []})
                window.location.reload()
                this.props.handleCloseAbove();
            })
            .catch(error => {
                console.log(error)
                if(error.response.status === 401){
                    this.setState({errors : error.response.data.errors})
                }
            });
    }

    reload = () => {
        console.log("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({alreadyDone:true})
                })
            })
            .catch(error => {
                console.log(error.response)
            })
        }
    }

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

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

    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">Editer 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' value={this.state.name}/>
                                </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}>
                                            <option value={this.state.categoryName}>{this.state.categoryName}</option>
                                            {this.state.categories.map((categorie) => 
                                                {if (this.state.categoryName !== categorie.name){
                                                return(<option key={categorie.id} value={categorie.id}>{categorie.name}</option>) 
                                                }else{return(null)}}
                                            )}
                                        </select>
                                    </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} value={this.state.description}/>
                            </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' value={this.state.quantity}/>
                                </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' value={this.state.price}/>
                                </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' value={this.state.code}/>
                            </div>
                            <div id="errorCodeBlock">
                                <p id="errorCode">{!this.state.code && this.state.errors.code}</p>
                            </div>
                        </div>
                        <div id="imageBlock">
                            <div id="imageBlockInput">
                                <Tooltip 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 ?
                                <p id="errorImage">{this.state.errors.image}</p>
                                : <p id="imageName">{this.state.image.name}</p>}
                                {!this.state.image &&
                                    <p id="imageName">{this.props.article.img}</p>
                                }
                            </div>
                        </div>
                            <button id="button" type='submit'>Modifier</button>
                    </form>
                </div>
            </div>
        </div>
        )}
    }

}

export default EditArticle