import {
  Card,
  Form,
  FormLayout,
  TextField,
  Button,
  Spinner,
  Select,
  SettingToggle,
  TextStyle
} from '@shopify/polaris';
import { Toast } from '@shopify/app-bridge-react';
import React from 'react';
import fetch from 'node-fetch';
import moment from 'moment';
import Cookies from 'js-cookie';


class ShopSettingsForm extends React.Component {

  state = {
    exportInterval: null,
    exportIntervalUnit: "minutes",
    intervalError: false,
    exportLocation: "",
    locationError: false,
    ftp_password: "",
    ftpPasswordError: false,
    unsaved: false,
    loading: true,
    webhooks: false,
    shopOrgin: Cookies.get('shopOrigin') && Cookies.get('shopOrigin').replace(".myshopify.com",""),
  };



  setExportLocation = (value) => {
    this.setState({
      exportLocation: value,
      unsaved: true
    })
  };

  setExportInterval= (value) => {
    let error;
    const parsed = parseInt(value);
    if (isNaN(parsed)) {
      error = "Interval must be an integer"
    }else{
      error = false;
    }

    this.setState({
      exportInterval: value,
      intervalError: error,
      unsaved: true
    });
  }

  setExportIntervalUnit = (value) => {
    const { exportInterval } = this.state;
    const minuteValue = this.getExportIntervalValueInMinutes(exportInterval);
    const unitValue = this.getExportIntervalValueInUnits(minuteValue, value);
    this.setState({
      exportIntervalUnit: value,
      exportInterval: unitValue
    });
  }

  getExportIntervalValueInMinutes = (value) => {
    const { exportIntervalUnit } = this.state;
    let unitValue;
    switch (exportIntervalUnit){
       case "hours":
          unitValue = value * 60;
          break;
       case "days":
          unitValue = value * 60 * 24;
          break;
       default:
          unitValue = value;
     }
     return unitValue
  }

  handleWebhookToggle = () => {
    const { webhooks } = this.state;
    this.setState({
      webhooks: webhooks ? false : true,
      unsaved: true
    })
  }

  setFtpPassword = (value)=>{
    //TODO: password validation
    this.setState({
        ftp_password:value,
        unsaved: true
    });
  }


  getExportIntervalValueInUnits(minuteValue, units){
    let unitValue = minuteValue;

    switch(units){
      case "days":
        unitValue = minuteValue / (60 * 24)
        break;
      case "hours":
        unitValue = minuteValue / 60
        break;
    }
    return unitValue;
  }

  handleSubmit = (_event) => {
    this.setState({
      loading: true,
    });

    const {exportInterval, exportLocation, exportIntervalUnit, webhooks, ftp_password} = this.state;

    const data = {
      exportInterval : this.getExportIntervalValueInMinutes(exportInterval),
      exportLocation,
      webhooks,
      ftp_password };
    const fetchUrl = `/settings`;

    fetch(fetchUrl, {
        method: "POST",
        body: JSON.stringify(data),
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        }
      })
      .then(response => {
        return response.json();
      })
      .then(this.setStateFromList);
  };

  setStateFromList = (json) => {

    const { exportIntervalUnit } = this.state;
    const settings = {...this.state};
    for(var i = 0; i < json.data.length; i++){
      const setting = json.data[i];
      settings[setting.key] = setting.value;
    }
    settings.exportInterval = this.getExportIntervalValueInUnits(settings.exportInterval, this.state.exportIntervalUnit);
    this.setState({
      ...settings,
      loading: false,
      unsaved: false
    });
  }

  componentDidMount(){
      const fetchUrl = `/settings`;

      fetch(fetchUrl, {
          method: "GET",
          headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
          }
        })
        .then(response => {
          return response.json();
        })
        .then(this.setStateFromList);
  }

  render() {
    const { setFtpPassword, handleSubmit, setExportInterval, setExportLocation, setExportIntervalUnit } = this;
    const { ftp_password, ftpPasswordError, exportInterval, exportIntervalUnit, exportLocation, loading, intervalError, locationError, unsaved, webhooks, shopOrgin } = this.state;

    const intervalUnitOptions = [
       {label: 'Days', value: 'days'},
       {label: 'Hours', value: 'hours'},
       {label: 'Minutes', value: 'minutes'}
     ];

     let formError = false;
     if(intervalError || locationError){
       formError = true
     }

     const webhookContentStatus = webhooks ? 'Disable' : 'Enable';
     const webhookTextStatus = webhooks ? 'enabled' : 'disabled';


    return (
          <Form onSubmit={handleSubmit}>
            { loading ?
              <Spinner accessibilityLabel="Loading Order Export" size="small" color="teal" />
            :
              <FormLayout>
                <SettingToggle
                  action={{
                    content: webhookContentStatus,
                    onAction: this.handleWebhookToggle,
                  }}
                  enabled={webhooks}
                >
                  Export on webhook is <TextStyle variation="strong">{webhookTextStatus}</TextStyle>.
                </SettingToggle>

                <TextField type="text"
                  disabled={loading}
                  label="Export Job Interval"
                  placeholder="1"
                  value={exportInterval.toString()}
                  onChange={setExportInterval}
                  helpText="Webhooks should catch all orders, this job is incase webhooks are off or as a backup to catch any orders missed."
                  error={intervalError}
                  connectedRight={
                    <Select
                      disabled={loading}
                      label="Unit"
                      labelInline
                      options={intervalUnitOptions}
                      onChange={setExportIntervalUnit}
                      value={exportIntervalUnit}
                   />
                  }
                />
                <TextField type="text"
                  disabled={loading}
                  label="FTP Password"
                  helpText={`FTP User: ${shopOrgin}`}
                  value={ftp_password}
                  onChange={setFtpPassword}
                  error={ftpPasswordError} />
                <TextField type="text"
                  disabled={loading}
                  label="Export Location"
                  placeholder=""
                  value={exportLocation}
                  onChange={setExportLocation}
                  error={locationError}
                />
                {unsaved ?
                <Button primary submit disabled={loading || formError}>Save</Button>
                :null}
              </FormLayout>
            }
          </Form>
      );
  }

}

export default ShopSettingsForm;
