import React from 'react';
import { fromUnixTime, formatDistanceToNow } from "date-fns";
import { formatInTimeZone } from 'date-fns-tz';
import superagent from 'superagent';
import { Table, Statistic, Label, Segment, Form } from 'semantic-ui-react'
import { DateInput } from 'semantic-ui-calendar-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 BigShipmentList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            shipments: [],
            limit: 250
        };
    }

    async componentDidMount() {
        this.setState({ loading: true });

        let schemas = await ApiUtils.getFabricatorSchemas();
        console.log(schemas);
        this.setState({ schemas });

        const params = new URLSearchParams(window.location.search);
        for (const [key, value] of params.entries()) {
            if (key === "limit") {
                this.setState({ limit: parseInt(value) });
            } else if (key === "status") {
                this.setState({ status: value });
            } else if (key === "minCreatedAt") {
                this.setState({
                    minCreatedAt: new Date(parseInt(value)).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })
                });
            } else if (key === "maxCreatedAt") {
                this.setState({
                    maxCreatedAt: new Date(parseInt(value)).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })
                });
            }
        }

        const res = await superagent.get(`/api/admin/shipper/stats`);
        console.log(res.body);
        this.setState({ stats: res.body });
        await this.onUpdateQuery();
    }

    async onTrackingLabelScanned(scannedSerialNumber) {
        this.setState({ loading: true, scannedSerialNumber: "" });
        const res = await superagent.get(`/api/admin/shipper/shipments?trackingNumber=${_.toUpper(scannedSerialNumber)}`);
        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();
        }
        console.log("onTrackingLabelScanned", scannedSerialNumber, res.body);
        this.setState({ shipments: res.body.items, stats: null, loading: false });
    }

    async onChange(e, { name, value }) {
        this.setState({ [name]: value }, this.onUpdateQuery.bind(this));
    }

    getUrlSearchParams(query) {
        const queryString = new URLSearchParams();
        queryString.append("limit", this.state.limit);

        if (query) {
            for (const [key, value] of Object.entries(query)) {
                queryString.append(key, value);
            }
        }
        return queryString;
    }

    async onUpdateQuery() {
        try {
            this.setState({ loading: true, queryResult: null });
            const query = {};
            if (this.state.status && this.state.status !== ApiUtils.ANY_VALUE) {
                query["status"] = this.state.status;
            }
            if (this.state.minCreatedAt) {
                query["minCreatedAt"] = new Date(this.state.minCreatedAt).getTime();
            }
            if (this.state.maxCreatedAt) {
                query["maxCreatedAt"] = new Date(this.state.maxCreatedAt).getTime();
            }
            const params = this.getUrlSearchParams(query);
            console.log(query, params);
            const newPathQuery = `${window.location.pathname}?${params.toString()}`;
            window.history.pushState(null, '', newPathQuery);
            const res = await superagent.get(`/api/admin/shipper/shipments?${params.toString()}`);
            this.setState({ shipments: res.body.items });
        } catch (err) {
            console.error(err);
        }
        this.setState({ loading: false });
    }

    render() {

        return (
            <BigShipperWrapper title="Shipments" loading={this.state.loading}>
                {this.state.stats &&
                    <Statistic.Group size="small">
                        {this.state.stats && this.state.stats.statsByType && this.state.stats.statsByType.map((stat, index) => {
                            return <Statistic>
                                <Statistic.Value>
                                    {stat.count}</Statistic.Value>
                                <Statistic.Label>{stat.type}</Statistic.Label>
                            </Statistic>
                        })}
                    </Statistic.Group>
                }


                {this.state.schemas && <Segment secondary>
                    <HandScannerInput type="trackingLabel" onScanFinished={this.onTrackingLabelScanned.bind(this)} />

                    <Form size="small" onSubmit={this.onChange.bind(this)}>
                        <Form.Group inline widths={2}>
                            <DateInput name="minCreatedAt"
                                autoComplete="off"
                                dateFormat='LL'
                                clearable
                                closable
                                width={2}
                                inlineLabel
                                label="From"
                                placeholder="Created After"
                                value={this.state.minCreatedAt}
                                iconPosition="left"
                                onChange={this.onChange.bind(this)} />
                            <DateInput name="maxCreatedAt"
                                autoComplete="off"
                                dateFormat='LL'
                                clearable
                                closable
                                width={2}
                                inlineLabel
                                label="To"
                                placeholder="Create Before"
                                value={this.state.maxCreatedAt}
                                iconPosition="left"
                                onChange={this.onChange.bind(this)} />
                            <Form.Select
                                width={2}
                                size="tiny"
                                label='Status'
                                name="status"
                                value={this.state.status}
                                options={this.state.schemas.BigShipmentStatusOptions}
                                onChange={this.onChange.bind(this)}
                            />
                        </Form.Group>
                    </Form>
                </Segment>}

                {!this.state.stats && <p>Found {this.state.shipments.length} items</p>}

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