import React from 'react';
import { fromUnixTime, formatDistanceToNow } from "date-fns";
import { formatInTimeZone } from 'date-fns-tz';
import superagent from 'superagent';
import { Table, Statistic, Label, Message } from 'semantic-ui-react'

import * as ApiUtils from '../CloudApi/ApiUtils.js';
import constants, { DEFAULT_TIMEZONE } from '../CloudApi/Constants.js';
import BigShipperWrapper from './BigShipperWrapper.jsx';
import BigShipmentsTable from './BigShipmentsTable.jsx';
import HandScannerInput from '../Util/HandScannerInput.jsx';

export default class BigShipmentPackingQueue extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            shipments: []
        };
    }

    async componentDidMount() {
        this.setState({ loading: true });
        const res = await superagent.get(`/api/admin/shipper/shipments?status=Packing&limit=100`);
        console.log(res.body);
        this.setState({ shipments: res.body.items, loading: false });
    }

    async onTrackingLabelScanned(scannedSerialNumber) {
        this.setState({ loading: true, scannedSerialNumber: "" });
        const res = await superagent.get(`/api/admin/shipper/shipments?trackingNumber=${_.toUpper(scannedSerialNumber)}`);
        console.log(res.body);
        if (res.body.items && res.body.items.length == 0) {
            const audio = new Audio("/misc/Error1.wav");
            audio.play();
        } else {
            const audio = new Audio("/misc/Notification3_2.wav");
            audio.play();
            // Redirect to the shipment page.
            this.props.history.push(`/shipper/shipment/${res.body.items[0].id}`);
        }
        this.setState({ loading: false });
    }

    render() {
        return (
            <BigShipperWrapper title="Packing List" loading={this.state.loading}>
                <HandScannerInput type="trackingLabel" onScanFinished={this.onTrackingLabelScanned.bind(this)} />

                <p>{this.state.shipments.length} items need to be packed</p>

                {this.state.shipments.length > 0 && <BigShipmentsTable shipments={this.state.shipments} />}
            </BigShipperWrapper>
        );
    }
}
