// LIBRARIES
import React, { Component } from 'react';
import { Modal, Button, DatePicker, Row, Col, notification } from "antd"
import { CSVLink } from "react-csv";
import { CSVReader } from 'react-papaparse'
import {API_CSV} from 'utils/StationApi'
import {API_UNI_OIL, API_PUT_BRANCH} from 'utils/StationApi'
import moment from 'moment'

  // HELPER FUNCTIONS
  const center = {
    lat: 16.1505,
    lng: 119.9856
  };
  const containerStyle = {
    width: '100%',
    height: '200px'
  };
  class UploadPricesModal extends Component {
    state= {
      updating: false,
      isGenerated: false,
      value: [],
      map: null,
      prices: [],
      date: "null",
      data: [],
      fuels: [],
      fuelsData: [],
      newFuel: [],
      csvData: [],
      btnDisabled: false,
      btnLoading: false
    };

    componentDidMount(){
      this.getStations()

    }



    componentDidUpdate(preProps, prevState){
      console.log("===componentWillUpdate===")
      if(this.state.csvData.length > 0){ 
        this.handleSuperManipulatingJutsu(this.state.csvData, this.state.date, prevState.date)
      }
    }

    getStations = async() => {
      try{
        const response = await API_CSV.get('stations/export/csv', '');
        this.setState({data: response.data})
        console.log(response)
      }catch(error){
        console.log(error)
      }
      this.getFuels()
    }

    handleForce = data => {
      this.setState({ data: data })
      console.log(data)
    };


    getFuels = async() => {
      try {
        const response = await API_UNI_OIL.get('fuels', '');
        if(response) {
          console.log(response.data.data, 'All Fuels')
          this.setState({ newFuel: response.data.data, fuelsData: response.data.data });
          let data = this.state.fuels
          data.map(fuel => {
            let newArray = this.state.newFuel.filter(function(element) {
              return element.id !== fuel.FuelId;
            });
            
            let allFuels = newArray.sort((a, b) => {
              if (a.name < b.name)
                return -1;
              if (a.name > b.name)
                return 1;
              return 0;
            })


            this.setState({newFuel: allFuels})
          })
        }
      } catch (error) {
        console.log(error)
      }
    }

    handleSuperManipulatingJutsu = (data, date, prevDate) => {
      
        var postData = []
        var keys = data[0].data
        var values = []
        let user = localStorage.getItem('user')

        if(keys[0].toLowerCase() != "name"){
          localStorage.setItem("headers", "null")
        }
        keys.splice(1, 0, "Update Schedule")
        keys.splice(2, 0, "User" )
        keys = keys.filter((a, b) => keys.indexOf(a) === b)

       

        for(var dd=1;dd<data.length;dd++){
          let ddata = data[dd]
          //CHECK IF VALUES ARE TRUE
          if(ddata.data[0] != ""){
            if(ddata.data[0].includes('"')){
              let dddd = ddata.data
              let vvvv = ddata.data[0].split('"')[1]
              dddd[0] = ddata.data[0].split(',"')[0]
              dddd.splice(1, 0, vvvv)              
              values.push(dddd)
            }else{
              let dddd = ddata.data
              values.push(dddd)
            }
          }
        }

        for(var a = 0; a < values.length; a++ ){
          var test = {}
          test["Name"] = values[a][0]
          test["Update Schedule"] = date
          test["User"] = user
          
          for(var aa=1;aa<values[a].length;aa++){
            test[keys[aa + 2]] = values[a][aa]
          }

          if(test["Name"]) postData.push(test)
        }
        console.log("postData", postData)
        console.log("JSON PostData", JSON.stringify(postData))

        localStorage.setItem("prices", JSON.stringify(postData))
    } 

    handleOnDrop = (data) => {
     this.setState({csvData: data})
     console.log(data)
     this.getFuels()
    }
   
    handleOnError = (err, file, inputElem, reason) => {
      console.log(err)
      localStorage.removeItem("prices")
      localStorage.removeItem("headers")
    }
   
    handleOnRemoveFile = (data) => {
      console.log(data)
      localStorage.removeItem("prices")
      localStorage.removeItem("headers")
    }

    onDateChange = (date, dateString) => {
      this.setState({date: dateString})
    }

    handleUpdatePrices = async () => {
      let sam = localStorage.getItem("prices")
      let empty = localStorage.getItem("headers")
      console.log(sam)
      console.log("Body", JSON.parse(sam))
      if(empty){
       localStorage.removeItem("headers")
        notification.error({ 
          message: "Error", 
          description: `Please recheck the CSV File, Invalid header.`,
          duration: 3
        });
      }
      else if(sam){
        this.setState({btnLoading:true, btnDisabled:true})
        try{
          const response = await API_CSV.post('stations/import/csv', JSON.parse(sam))
          console.log(response)
          if(response.data.code == 200){
            this.setState({btnLoading:false, btnDisabled:false})
            notification.success({
              message: 'Success',
              description: `Upload Successful.`,
            });
          this.props.cancel()
          }
          else if(response.data.code == 404){
            this.setState({btnLoading:false, btnDisabled:false})
            notification.error({
              message: 'Error',
              description: `Please recheck the CSV File, Some fuels doesn't exist.`,
              duration: 3
            });
            this.props.cancel()
          }
          else if(response.data.code == 500){
            this.setState({btnLoading:false, btnDisabled:false})
            notification.error({
              message: 'Error',
              description: `Please recheck the CSV File, Some stations doesn't exist.`,
              duration: 3
            });
            this.props.cancel()
          }
        }
        catch(error){
          console.log(error)
          this.setState({btnLoading:false, btnDisabled:false})
          notification.error({
            message: 'Error',
            description: `Something went wrong loading the data, Please try again.`,
            duration: 3
          });
          this.props.cancel()
        }
      }
      else{
        notification.warning({ 
          message: "Warning", 
          description: `Please upload a csv file.`,
          duration: 3
        });
      }
      localStorage.removeItem("prices")
      localStorage.removeItem("headers")
      setTimeout(function(){
        window.location.reload();
     }, 3000);
    }

    disabledDate(current) {
      // Can not select days before today and today
      return current && current < moment().startOf('day');
    }

    onOk(value) {
      console.log('onOk: ', value);
    }
 
    render() {
      let prices = this.prices? this.prices : null
      console.log(prices)
      let { btnDisabled, btnLoading } = this.state;
      return (
        <Modal id='uploadPricesModal'
          title="Upload Prices"
          visible={this.props.visible}
          closable={false}
          bodyStyle={{paddingTop: '5px'}}
          footer={[
            <Button key="back" onClick={this.props.cancel}>
              Close
            </Button>,
            <Button key="ok" 
            disabled={btnDisabled}
            loading={btnLoading} 
            style={{ 
              opacity: btnDisabled ? 0.5 : 'initial'
            }}
            onClick={this.handleUpdatePrices}>
              Upload New Pricelist
            </Button>
          ]}
        >
          <CSVLink data={this.state.data}>Download Prices Template</CSVLink><br />
          <CSVReader
            onDrop={this.handleOnDrop}
            onError={this.handleOnError}
            addRemoveButton
            removeButtonColor='#659cef'
            onRemoveFile={this.handleOnRemoveFile}
          >
            <span>Drop CSV file here or click to upload.</span>
          </CSVReader>
          <Row>
          <Col>
            </Col>
            <Col>
              <DatePicker 
                format='YYYY-MM-DD HH:mm'
                onChange={this.onDateChange}
                showTime={{ format: 'HH:mm' }}
                onOk={this.onOk}
                disabledDate={this.disabledDate}
                style={{width: '250px', marginRight: '15px', marginTop: '10px', marginLeft: '100px', marginBottom: '15px' }}
              />
            </Col>
           
            <Col>
            <ul>
              <li><span>This is for scheduling update for group or station.</span></li>
              <li>Schedule will be applied to uploaded stations.</li>
            </ul>
            <i>If you want to schedule update for another group of stations please upload new file.</i>

            </Col>
          
          </Row>
        </Modal>
      );
    }
  }
  
  export default UploadPricesModal;
