import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import React, { useState } from "react";
import Box from "@material-ui/core/Box";
import Button from "@material-ui/core/Button";
import Table from "@material-ui/core/Table";
import TableBody from "@material-ui/core/TableBody";
import TableCell from "@material-ui/core/TableCell";
import TableHead from "@material-ui/core/TableHead";
import TableRow from "@material-ui/core/TableRow";
import useLabelHelp from "./use-label-help";
import usePosthog from "../../hooks/use-posthog";
import CircularProgress from "@material-ui/core/CircularProgress";
import { useAppConfig } from "../AppConfig";
import useDataset from "../../hooks/use-dataset";
import { setIn } from "seamless-immutable";
import useEventCallback from "use-event-callback";
var usdFormatter = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD"
});
var preciseUSDFormatter = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD",
  maximumFractionDigits: 4,
  minimumFractionDigits: 2
});
export var LabelHelpSetup = function LabelHelpSetup(_ref) {
  var onChangeActiveStep = _ref.onChangeActiveStep,
      onError = _ref.onError;

  var _useAppConfig = useAppConfig(),
      fromConfig = _useAppConfig.fromConfig,
      setInConfig = _useAppConfig.setInConfig;

  var _useDataset = useDataset(),
      _useDataset2 = _slicedToArray(_useDataset, 2),
      dataset = _useDataset2[0],
      setDataset = _useDataset2[1];

  var _useLabelHelp = useLabelHelp(),
      variables = _useLabelHelp.variables,
      _useLabelHelp$totalCo = _useLabelHelp.totalCost,
      totalCost = _useLabelHelp$totalCo === void 0 ? 0 : _useLabelHelp$totalCo,
      _useLabelHelp$formula = _useLabelHelp.formulaFunc,
      formulaFunc = _useLabelHelp$formula === void 0 ? function () {
    return 0;
  } : _useLabelHelp$formula,
      _useLabelHelp$myCredi = _useLabelHelp.myCredits,
      myCredits = _useLabelHelp$myCredi === void 0 ? function () {
    return 0;
  } : _useLabelHelp$myCredi;

  var posthog = usePosthog();

  var _useState = useState(false),
      _useState2 = _slicedToArray(_useState, 2),
      isCreating = _useState2[0],
      setIsCreating = _useState2[1];

  var onStartLabelHelp = useEventCallback( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
    var response;
    return _regeneratorRuntime.wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            onError(null);
            setIsCreating(true);
            _context2.next = 4;
            return fetch("https://labelhelp.universaldatatool.com/api/submit", {
              method: "POST",
              body: JSON.stringify({
                dataset: dataset,
                price: totalCost,
                api_key: fromConfig("labelhelp.apikey")
              }),
              headers: {
                "Content-Type": "application/json"
              }
            }).then( /*#__PURE__*/function () {
              var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(r) {
                return _regeneratorRuntime.wrap(function _callee$(_context) {
                  while (1) {
                    switch (_context.prev = _context.next) {
                      case 0:
                        if (r.ok) {
                          _context.next = 6;
                          break;
                        }

                        _context.t0 = Error;
                        _context.next = 4;
                        return r.text();

                      case 4:
                        _context.t1 = _context.sent;
                        throw new _context.t0(_context.t1);

                      case 6:
                        return _context.abrupt("return", r.json());

                      case 7:
                      case "end":
                        return _context.stop();
                    }
                  }
                }, _callee);
              }));

              return function (_x) {
                return _ref3.apply(this, arguments);
              };
            }()).catch(function (e) {
              onError(e.toString());
              throw e;
            });

          case 4:
            response = _context2.sent;

            if (response) {
              _context2.next = 8;
              break;
            }

            onError("Empty response from server");
            return _context2.abrupt("return", null);

          case 8:
            setIsCreating(false);
            setDataset(setIn(dataset, ["labelHelp"], {
              url: response.custom_id,
              totalCost: totalCost
            }));
            onChangeActiveStep("running");
            posthog.capture("start_label_help_button_clicked");

          case 12:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2);
  })));
  return /*#__PURE__*/React.createElement(Box, null, /*#__PURE__*/React.createElement(Table, null, /*#__PURE__*/React.createElement(TableHead, null, /*#__PURE__*/React.createElement(TableRow, null, /*#__PURE__*/React.createElement(TableCell, null, "Item"), /*#__PURE__*/React.createElement(TableCell, null, "Quantity"), /*#__PURE__*/React.createElement(TableCell, null, "Unit Cost"), /*#__PURE__*/React.createElement(TableCell, null, "Cost / Sample"), /*#__PURE__*/React.createElement(TableCell, null, "Total"))), /*#__PURE__*/React.createElement(TableBody, null, Object.keys(variables || {}).map(function (varName) {
    return /*#__PURE__*/React.createElement(TableRow, null, /*#__PURE__*/React.createElement(TableCell, {
      style: {
        textTransform: "capitalize"
      }
    }, varName.replace(/_/g, " ")), /*#__PURE__*/React.createElement(TableCell, null, variables[varName]), /*#__PURE__*/React.createElement(TableCell, null, varName === "sample_count" ? "" : preciseUSDFormatter.format((totalCost - formulaFunc(_objectSpread(_objectSpread({}, variables), {}, _defineProperty({}, varName, 0)))) / variables.sample_count / (variables[varName] === 0 ? 1 : variables[varName]))), /*#__PURE__*/React.createElement(TableCell, null, usdFormatter.format((totalCost - formulaFunc(_objectSpread(_objectSpread({}, variables), {}, _defineProperty({}, varName, 0)))) / variables.sample_count)), /*#__PURE__*/React.createElement(TableCell, null));
  }), /*#__PURE__*/React.createElement(TableRow, null, /*#__PURE__*/React.createElement(TableCell, null, "Total Cost"), /*#__PURE__*/React.createElement(TableCell, null), /*#__PURE__*/React.createElement(TableCell, null), /*#__PURE__*/React.createElement(TableCell, null), /*#__PURE__*/React.createElement(TableCell, null, usdFormatter.format(totalCost))), /*#__PURE__*/React.createElement(TableRow, null, /*#__PURE__*/React.createElement(TableCell, null, "Time to Complete"), /*#__PURE__*/React.createElement(TableCell, null), /*#__PURE__*/React.createElement(TableCell, null), /*#__PURE__*/React.createElement(TableCell, null), /*#__PURE__*/React.createElement(TableCell, null, "1-3 days")))), /*#__PURE__*/React.createElement(Box, {
    display: "flex",
    justifyContent: "flex-end",
    alignItems: "center",
    padding: 2,
    paddingTop: 4
  }, /*#__PURE__*/React.createElement(Box, null, "Credits: ", usdFormatter.format(myCredits)), /*#__PURE__*/React.createElement(Box, {
    flexGrow: 1
  }), /*#__PURE__*/React.createElement(Button, {
    onClick: function onClick() {
      setInConfig("labelhelp.apikey", null);
      posthog.capture("api_key_button_clicked");
    },
    variant: "outlined"
  }, "API Key"), /*#__PURE__*/React.createElement(Button, {
    color: myCredits < totalCost ? "primary" : "none",
    style: {
      marginLeft: 12
    },
    variant: "outlined",
    href: "https://labelhelp.universaldatatool.com#addcredits",
    onClick: function onClick() {
      posthog.capture("add_credits_button_clicked");
    }
  }, "Add Credits"), /*#__PURE__*/React.createElement(Button, {
    onClick: onStartLabelHelp,
    style: {
      marginLeft: 12
    },
    variant: "outlined",
    disabled: isCreating,
    color: myCredits >= totalCost ? "primary" : "none"
  }, !isCreating ? "Start Label Help" : /*#__PURE__*/React.createElement(CircularProgress, {
    size: 16
  }))));
};
export default LabelHelpSetup;