import React from 'react';
import '../../css/Views/stock.css';
import Header from '../Components/Header';
import Articles from '../Components/Articles';
import ArticlesByCategory from '../Components/ArticlesByCategory';
import Navbar from '../Components/Navbar';
import CreateArticle from '../Components/CreateArticle';
import 'react-perfect-scrollbar/dist/css/styles.css';
import EditArticle from '../Components/EditArticle';
import CreateCategory from '../Components/CreateCategory';
import Footer from '../Components/Footer';
import SearchBar from '../Components/SearchBar';
import axios from 'axios';
import AppLoader from '../Components/AppLoader';
import Categories from '../Components/Categories';
import EditCategory from '../Components/EditCategory';
import Sort from '../Components/Sort';
import { Link } from 'react-router-dom';
import Selected from '../Components/Selected';

export default class Stock extends React.Component {

  constructor(props){
    super(props)
    this.state = {
      onNewArticle:false,
      onEditArticle:false,
      onNewCategory:false,
      onCategories:false,
      onEditCategory:false,
      article:{},
      imageFile:{},
      articles:[],
      categoryToModify:'',
      categorySorted:false,
      onSortedCategories:false,
      onSearch:false,
      lowToHigh: true,
      selectedArticles:[],
      counter:0,
      code:''
    }
  }

  componentDidMount() {
    this.getArticles()
  }

  select = () => {

    this.setState({counter:this.state.counter+1},()=>{
      console.log(this.state.counter)
    })

  }

  deselect = () => {

    this.setState({counter:this.state.counter-1},()=>{
      console.log(this.state.counter)
    })

  }

  // Implémenter la fonction sortArticles :
  sortArticles = (sortType) => {
      
    let sorted;
    //TRI PAR ORDRE ALPHABETIQUE OU PRIX
    if (sortType === "name"){
      this.setState({orderIsHidden: false}) //choix d'ordre possible
      if (this.state.lowToHigh) {
        //ordre alphabétique croissant
        sorted = [...this.state.articles].sort((a, b) => a.name.localeCompare(b.name))
      } else {
        //ordre alphabétique décroissant
        sorted = [...this.state.articles].sort((a, b) => b.name.localeCompare(a.name))
      }
    } else if (sortType === "price") {
      console.log('tri pix')
      this.setState({orderIsHidden: false}) //choix d'ordre possible
      if (this.state.lowToHigh) {
        //ordre croissant
        sorted = [...this.state.articles].sort((a, b) => a.price - b.price)
      } else {
        //ordre décroissant
        sorted = [...this.state.articles].sort((a, b) => b.price - a.price)
      }
      
    } else {
      console.log('autre 1')
      this.setState({orderIsHidden: true})
      this.setState({lowToHigh: false})
      sorted = [...this.state.articles].sort((a, b) => b[sortType] - a[sortType]);
    }

    //TRI PAR CATEGORIE
    if (sortType === 'category_id'){
      this.setState({articles:sorted},() => {
        this.setState({onSortedCategories:true})
      })
    }else{
      console.log('autre 2')
      this.setState({articles:sorted},() => {
        console.log(this.state.articles)
        this.setState({onSortedCategories:false})
      })
    }
  }

  getArticles = () => {
    axios.get('https://etud.insa-toulouse.fr/~proximo/v2/api/articles')
        .then(res => {
            this.setState({articles : res.data}, () => {
                console.log(this.state.articles)
                this.sortArticles("name")
            })
        })
        .catch(error => {
            console.log(error.response)
        })
  }

  handleNewArticle = () => {
        this.setState({onNewArticle:true},()=>{
          console.log(this.state.onNewArticle)
        })
  }

  handleCloseNewArticle = () => {
    this.setState({onNewArticle:false})
  }

  handleArticleEdition = (article) => {
    this.setState({article:article})
    this.setState({onEditArticle:true});
  }

  handleCloseEditArticle = () => {
    this.setState({onEditArticle:false})
  }

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

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

  handleCategories = category => {
    this.setState({currentCategory:category})
    this.setState({onCategories:true})
  }

  handleCloseCategories = () => {
    this.setState({onCategories:false})
  }

  handleEditCategory = category => {
    this.handleCloseCategories()
    this.setState({categoryToModify:category})
    this.setState({onEditCategory:true})
  }

  handleCloseEditCategory = () => {
    this.setState({onEditCategory:false})
  }

  // handleChangeSortType = (e) => {
  //   console.log(e.target.value)
  //   this.setState({sortType:e.target.value},()=>{
  //     if (this.state.sortType === "Ordre Alphabétique"){
  //       this.sortArticles("name")
  //     } else if(this.state.sortType === "Catégorie"){
  //       this.sortArticles("category_id")
  //     } else if(this.state.sortType === "Quantité"){
  //       this.sortArticles("quantity")
  //     } else if(this.state.sortType === "Prix"){
  //       this.sortArticles("price");
  //     } 

  //   })
  // }

  handleChangeSortType = (e) => {
    console.log(e.target.value)
    this.setState({sortType: e.target.value}, () => {
      this.sortArticles(this.state.sortType)
    })
  }

  //Gère le choix de tri par ordre croissant ou décroissant quand c'est possible avec le tri actuel
  handleChangeSortOrder = e => {
    this.setState({lowToHigh: (this.state.lowToHigh + 1) % 2},() => {
      console.log(this.state.sortType)
      this.sortArticles(this.state.sortType);
    });
  }

  searchArticles = () => {
    this.setState({onSearch:true})
    let bodyFormData = new FormData()
    bodyFormData.set('search',this.state.search)
    axios.post('https://etud.insa-toulouse.fr/~proximo/v2/api/articles',bodyFormData)
            .then(res => {
                this.setState({articles : res.data}, () => {
                    console.log(this.state.articles)
                })
            })
            .catch(error => {
                console.log(error.response)
            })
  }

  handleSearchChange = event => {
    this.setState({search : event.target.value},()=>
    {
      this.searchArticles();
    })
  }

  handleSubmit = event => {
    event.preventDefault()
    this.searchArticles();
  }

  closeWithEscape = (e) => {
    if (e.keyCode === 27){
      if (this.state.onEditArticle){
        this.handleCloseEditArticle()
      } else if(this.state.onNewArticle){
        this.handleCloseNewArticle()
      } else if(this.state.onNewCategory){
        this.handleCloseNewCategory()
      } else if(this.state.onEditCategory){
        this.handleCloseEditCategory()
      } else if(this.state.onCategories){
        this.handleCloseCategories()
      }
    }
  }

  render() {
    if (!sessionStorage.getItem('token')){
      return (<div id="errorRouteBlock"><div id="errorRouteTitle">ERREUR </div><br/><div id="errorRouteTxt">Vous n'êtes pas connecté</div><br/><Link id="link" to='/'>Retourner à l'Accueil</Link></div>)
    } else {
      return (
          <div id="stock" tabIndex={-1} onKeyDown={this.closeWithEscape}>
              <Header title='Le Stock'/>
              <Navbar handleNewArticle={this.handleNewArticle} handleNewCategory={this.handleNewCategory} right="Le Ticket de Caisse" left="Créer" leftLeft="Article" leftMiddle="|" leftRight="Catégorie" redirect="/ticket"/>
              {this.state.onNewArticle ?
                <CreateArticle keepNewArticle={this.handleNewArticle} handleCloseAbove={this.handleCloseNewArticle}/>
              : null}
              <SearchBar handleSubmit={this.handleSubmit} handleSearchChange={this.handleSearchChange}/>
              <div id="sortBlock">
                <Sort handleChangeSortType={this.handleChangeSortType} handleChangeSortOrder={this.handleChangeSortOrder} orderIsHidden={this.state.orderIsHidden} lowToHigh={this.state.lowToHigh}/>
              </div>
              <div id="selectedBlock">
                <Selected counter={this.state.counter}/>
              </div>
              <div id="articleBlock">
              {this.state.articles && this.state.articles[0] ? 
                this.state.onSortedCategories ?
                  <ArticlesByCategory onSearch={this.state.onSearch} handleCategories={this.handleCategories} articles={this.state.articles} editionArticle={this.handleArticleEdition}/>
                : <Articles deselect={this.deselect} select={this.select} handleCategories={this.handleCategories} articles={this.state.articles} editionArticle={this.handleArticleEdition}/>
              : <AppLoader/>
              }
              </div>
              {this.state.onEditArticle ?
                <EditArticle handleCloseAbove={this.handleCloseEditArticle} article={this.state.article}/>
              : null}
              {this.state.onNewCategory ?
                <CreateCategory reload={true} handleCloseAbove={this.handleCloseNewCategory}/>
              : null }
              {this.state.onCategories ?
                <Categories handleEditCategory={this.handleEditCategory} currentCategory={this.state.currentCategory} handleCloseAbove={this.handleCloseCategories}/>
              : null}
              {this.state.onEditCategory ?
                <EditCategory category={this.state.categoryToModify} handleCloseAbove={this.handleCloseEditCategory}/>
              : null}
              <Footer/>
          </div>
      )}
    }
  }