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, Progress, Header, Transition, Icon, Segment } 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 BigShipmentFulfillmentQueue extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            currentShipment: null,
            courierCounts: {},
            preparingToShipItems: [],
            preparedTodayItems: [],
            waitingForPickupItems: [],
        };
    }

    async componentDidMount() {
        return this.reload();
    }

    async reload() {
        let courierCounts = {};
        let today = new Date();
        today.setHours(0, 0, 0, 0);
        this.setState({ loading: true });
        const res = await superagent.get(`/api/admin/shipper/shipments?status=PreparingToShip`);
        this.setState({ preparingToShipItems: res.body.items });
        const res3 = await superagent.get(`/api/admin/shipper/shipments?minCreatedAt=${today.getTime()}`);
        // sort res4.body.items by currentShippingLabel.rate.provider
        res3.body.items.sort((a, b) => {
            if (a.currentShippingLabel && b.currentShippingLabel) {
                return a.currentShippingLabel.rate.provider.localeCompare(b.currentShippingLabel.rate.provider);
            } else if (a.currentShippingLabel) {
                return -1;
            } else if (b.currentShippingLabel) {
                return 1;
            } else {
                return 0;
            }
        });
        // tally up the counts per courier
        res3.body.items.forEach((shipment) => {
            if (shipment.currentShippingLabel && shipment.currentShippingLabel?.rate?.provider) {
                if (!courierCounts[shipment.currentShippingLabel.rate.provider]) {
                    courierCounts[shipment.currentShippingLabel.rate.provider] = 0;
                }
                courierCounts[shipment.currentShippingLabel.rate.provider]++;
            }
        });
        this.setState({ preparedTodayItems: res3.body.items, courierCounts, loading: false });

        const res2 = await superagent.get(`/api/admin/shipper/shipments?status=WaitingForPickup&limit=100`);
        console.log(res2.body);
        this.setState({ waitingForPickupItems: res2.body.items, count: res2.body.count });
    }

    async onTrackingLabelScanned(scannedSerialNumber) {
        this.setState({ loading: true, scannedSerialNumber: "" });
        const res = await superagent.get(`/api/admin/shipper/shipments?trackingNumber=${_.toUpper(scannedSerialNumber)}&status=PreparingToShip&limit=100`);
        if (res.body.items && res.body.items.length === 1) {
            const audio = new Audio("/misc/Notification3_2.wav");
            audio.play();

            this.setState({ loading: false, currentShipments: res.body.items });

            // Update the status of the shipment.
            try {
                const res2 = await superagent.put(`/api/admin/shipper/shipment/${res.body.items[0].id}`)
                    .send({
                        action: "ShipIt"
                    });
                await this.setState({ currentShipments: [] });
                const audio2 = new Audio("/misc/Notification24.wav");
                audio2.play();
            } catch (e) {
                console.log(e);
            }

            this.reload();
        } else {
            const audio = new Audio("/misc/Error1.wav");
            audio.play();
        }
        console.log("onTrackingLabelScanned", scannedSerialNumber, res.body);
        this.setState({ loading: false });
    }

    render() {

        let body;
        if (this.state.preparingToShipItems.length === 0) {
            body = (
                <Transition visible={!this.state.loading} animation='bounce' duration={500}>
                    <Message icon color="green">
                        <Icon name='check' />
                        <Message.Content>
                            <Message.Header>All items have been fulfilled!</Message.Header>
                        </Message.Content>
                    </Message>
                </Transition>
            );
        } else if (this.state.currentShipments && this.state.currentShipments.length > 0) {
            body = (
                <Transition visible={!this.state.loading} animation='fade' duration={500}>
                    <Segment color="green">
                        <Message icon color="green">
                            <Icon name='circle notched' loading />
                            <Message.Content>
                                <Message.Header>Completing fulfillment</Message.Header>
                            </Message.Content>
                        </Message>
                        <BigShipmentsTable shipments={this.state.currentShipments} />
                    </Segment>
                </Transition>
            );
        } else {
            body = (
                <HandScannerInput type="trackingLabel" onScanFinished={this.onTrackingLabelScanned.bind(this)} />
            );
        }

        return (
            <BigShipperWrapper title={`${this.state.preparingToShipItems.length}/${this.state.preparingToShipItems.length + this.state.waitingForPickupItems.length} items to fulfill`} loading={this.state.loading}>
                <Progress value={this.state.waitingForPickupItems.length} total={this.state.preparingToShipItems.length + this.state.waitingForPickupItems.length} progress='ratio' indicating />

                {body}

                <Header as="h2">{this.state.preparingToShipItems.length} items to fulfil</Header>
                <BigShipmentsTable shipments={this.state.preparingToShipItems} />

                <Header as="h2">{this.state.preparedTodayItems.length} items prepared today</Header>
                <Header as="h3">{Object.entries(this.state.courierCounts).map(([courier, count]) => `${courier}: ${count}`).join(", ")}</Header>
                <BigShipmentsTable shipments={this.state.preparedTodayItems} />

                <Header as="h2">Newest {this.state.waitingForPickupItems.length}/{this.state.count} items waiting for pickup:</Header>
                <BigShipmentsTable shipments={this.state.waitingForPickupItems} />

            </BigShipperWrapper>
        );
    }
}
