import React from 'react';
import { fromUnixTime, formatDistanceToNow } from "date-fns";
import { formatInTimeZone } from 'date-fns-tz';
import superagent from 'superagent';

import { Message, Segment, Modal, Header, Icon, Button, Table, Form, Divider, Label } from 'semantic-ui-react'
import BigShipperWrapper from './BigShipperWrapper.jsx';
import * as ApiUtils from '../CloudApi/ApiUtils.js';
import BigOrderComponent from '../BigOrders/BigOrderComponent.jsx';
import HandScannerInput from '../Util/HandScannerInput.jsx';
import BigOrdersQuery from '../BigOrders/BigOrdersQuery.jsx';

export default class BigShipperNextOrder extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            nextInventoryItems: [],
            currentShipment: null,
            productDatabaseOptions: []
        };
    }

    async componentDidMount() {
        //this.setState({ loading: true });
        let schemas = await ApiUtils.getFabricatorSchemas();
        this.setState({ schemas });
    }

    async onScannedSerialNumberFinished(scannedSerialNumber) {
        if (scannedSerialNumber.startsWith("bs")) {
            scannedSerialNumber = scannedSerialNumber.toUpperCase();
        }

        this.setState({ loading: true, scannedSerialNumber: "" });
        const res = await superagent.get(`/api/admin/inventory/items?serialNumber=${scannedSerialNumber}`);
        console.log(res.body);
        this.setState({ items: res.body.items, binNumber: res.body.binNumber, menuLoading: false });

        const res2 = await superagent.get(`/api/admin/inventory/hint?serialNumber=${scannedSerialNumber}`);
        console.log(res2.body);
        this.setState({ hint: res2.body.hint, newItemSerialNumber: scannedSerialNumber, loading: false });
    }

    async onCreateShipment(bigOrderId, shipmentGroupId) {
        this.setState({ loading: true });
        try {
            const res = await superagent.post(`/api/admin/shipper/shipment`).send({
                bigOrderId,
                shipmentGroupId
            });
            window.location.href = `/shipper/shipment/${res.body.id}`;
        } catch (e) {
            console.log(e);
            this.setState({ loading: false });
        }
    }

    async onUpdateQuery(params) {
        this.setState({ loading: true, inventoryItems: [], bigOrder: null });
        let shipperResults = [];

        try {
            const result = await superagent.get(`/api/admin/shipper/next3?${params.toString()}`);
            shipperResults = result.body;
        } catch (e) {
            console.log(e);
        }

        this.setState({
            shipperResults,
            loading: false
        });
    }

    render() {

        let bigShipperResults = null;
        if (this.state.shipperResults && this.state.shipperResults.length > 0) {
            bigShipperResults = this.state.shipperResults.map((result) => (
                <>
                    <BigOrderComponent key={result.bigOrder.id} allowClicks={false} asTableRow={true} schemas={this.state.schemas} bigOrder={result.bigOrder} shipmentGroupId={result.shipmentGroupId} showDetail={false} />
                    <Table.Row>
                        <Table.Cell colSpan="7">
                            <Button fluid primary content='Create Shipment' type='submit' onClick={this.onCreateShipment.bind(this, result.bigOrder.id, result.shipmentGroupId)} />
                            <br />
                        </Table.Cell>
                    </Table.Row>
                </>
            ));
        } else {
            bigShipperResults = <Message warning>
                <Message.Header>No big orders to ship</Message.Header>
                <p>There are no big orders to ship with this selection!</p>
            </Message>;
        }


        return (
            <BigShipperWrapper title="🚢 Big Shipper 🚢" loading={this.state.loading}>
                <BigOrdersQuery limit={25} schemas={this.state.schemas} onQueryUpdated={this.onUpdateQuery.bind(this)} productDatabaseOptions={this.state.productDatabaseOptions} />

                {this.state.loading && <Header as='h2'>Looking for an order to ship...</Header>}

                {this.state.shipperResults && <Header as='h2'>📦 Showing Next {this.state.shipperResults.length} Orders Ready To Ship</Header>}

                {!this.state.loading && (
                    <Table celled>
                    {bigShipperResults}
                    </Table>
                )}

            </BigShipperWrapper>
        );
    }
}
