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

class OrderManualSubmitForm extends React.Component {

  state = {
    orderNumber : "",
    loading : false,
    exportType : "full",
    toastMessage : null,
  };

  setOrderNumber = (value) => {
    this.setState({
      orderNumber: value
    })
  };

  setExportChange = (value) => {
    this.setState({
      exportType: value
    })
  }

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

    const {orderNumber, exportType} = this.state;
    const data = { exportType: exportType };
    const fetchUrl = `/order/${orderNumber}/export`;

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

  dismissToast = () => {
    this.setState({
      toastMessage : null
    })
  };

  render() {
    const { handleSubmit, setOrderNumber, setExportChange, dismissToast } = this;
    const { exportType, orderNumber, loading, toastMessage } = this.state;

    const exportOptions = [
       {label: 'Full', value: 'full'},
       {label: 'Rental', value: 'rental'},
       {label: 'Retail', value: 'retail'}
     ];

    return (
          <Form onSubmit={handleSubmit}>
              <TextField type="text"
                disabled={loading}
                label="Export Order"
                placeholder="Order ID (Not order #)"
                value={orderNumber}
                onChange={setOrderNumber}
                helpText="This should be a 13 digit code at the end of the order url in admin .../admin/orders/1972923007115"
                connectedLeft={
                  <Select
                    disabled={loading}
                    label="Export type"
                    labelInline
                    options={exportOptions}
                    onChange={setExportChange}
                    value={exportType}
                 />
                }
                connectedRight={
                  <Button submit disabled={loading}>Submit</Button>
                }
              />
              { loading ?
                <Spinner accessibilityLabel="Loading Order Export" size="small" color="teal" />
              : null }
              { toastMessage ?
                <Toast content={toastMessage} onDismiss={dismissToast} />
              : null}
          </Form>
      );
  }

}

export default OrderManualSubmitForm;
