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

import * as ApiUtils from '../CloudApi/ApiUtils.js';
import constants, { DEFAULT_TIMEZONE } from '../CloudApi/Constants.js';
import BigShipperWrapper from './BigShipperWrapper.jsx';
import { Grid, Table, Button, Label, Message } from 'semantic-ui-react'

export default class BigShipmentLabel extends React.Component {
    constructor(props) {
        super(props);
        this.state = {};
        this.iframeRef = React.createRef();
    }

    autoPrintIframe = () => {
        if (this.props.autoPrint) {
            this.printIframe();
        }
    }

    printIframe = () => {
        const iframe = this.iframeRef.current;
        if (iframe) {
            iframe.focus();
            iframe.contentWindow.print();
        }
    }

    render() {
        let shippingLabel = this.props.bigShipment.currentShippingLabel;

        // Shipping label values changed between Shippo API versions.
        let objectCreated = shippingLabel.object_created || shippingLabel.objectCreated;
        let provider = shippingLabel.rate ? (shippingLabel.rate.provider) : "";
        let servicelevelName = shippingLabel.rate ? (shippingLabel.rate.servicelevel_name || shippingLabel.rate.servicelevelName) : "";
        let amount = shippingLabel.rate ? (shippingLabel.rate.amount) : "";
        let currency = shippingLabel.rate ? (shippingLabel.rate.currency) : "";
        let trackingUrlProvider = shippingLabel.tracking_url_provider || shippingLabel.trackingUrlProvider;
        let trackingNumber = shippingLabel.tracking_number || shippingLabel.trackingNumber;
        let factoryPrintedLabelUrl = shippingLabel.upload_label_url || shippingLabel.uploadLabelUrl;
        let commercialInvoiceUrl = shippingLabel.commercial_invoice_url || shippingLabel.commercialInvoiceUrl;
        let trackingLabelUrl = shippingLabel.label_url || shippingLabel.labelUrl;

        let createdAt, fromNow;

        console.log(shippingLabel);

        if (objectCreated) {
            let createdAtDateTime = new Date(objectCreated);
            createdAt = formatInTimeZone(createdAtDateTime, DEFAULT_TIMEZONE, 'PPPp z');
            fromNow = formatDistanceToNow(createdAtDateTime, { addSuffix: true });
        }

        return (
            <Grid celled columns="2">
                <Grid.Column width={6}>
                    <Table celled>
                        <Table.Body>
                            <Table.Row>
                                <Table.Cell>Provider</Table.Cell>
                                <Table.Cell>{provider}</Table.Cell>
                            </Table.Row>
                            <Table.Row>
                                <Table.Cell>Service Level</Table.Cell>
                                <Table.Cell>{servicelevelName}</Table.Cell>
                            </Table.Row>
                            <Table.Row>
                                <Table.Cell>Amount</Table.Cell>
                                <Table.Cell>{amount} ({currency})</Table.Cell>
                            </Table.Row>
                            {trackingNumber && <Table.Row>
                                <Table.Cell>Tracking Number</Table.Cell>
                                <Table.Cell><a style={{ 'textDecoration': 'underline' }} href={trackingUrlProvider}>{trackingNumber}</a></Table.Cell>
                            </Table.Row>}
                            <Table.Row>
                                <Table.Cell>Files</Table.Cell>
                                <Table.Cell>
                                    {factoryPrintedLabelUrl && (<a style={{ 'textDecoration': 'underline' }} href={factoryPrintedLabelUrl}>Factory printed label</a>)}<br />
                                    {commercialInvoiceUrl && <> <a style={{ 'textDecoration': 'underline' }} href={commercialInvoiceUrl}>Commercial Invoice</a><br /></>}
                                    {trackingLabelUrl && <><a style={{ 'textDecoration': 'underline' }} href={trackingLabelUrl}>Tracking label</a><br /></>}
                                </Table.Cell>
                            </Table.Row>
                            <Table.Row>
                                <Table.Cell>Status</Table.Cell>
                                <Table.Cell>{shippingLabel.test ? <Label color="red">TEST LABEL</Label> : <Label color="green">{shippingLabel.status}</Label>}</Table.Cell>
                            </Table.Row>
                            <Table.Row>
                                <Table.Cell>Created At</Table.Cell>
                                <Table.Cell>{createdAt} ({fromNow})</Table.Cell>
                            </Table.Row>
                        </Table.Body>
                    </Table>
                </Grid.Column>
                <Grid.Column width={10}>
                    <iframe ref={this.iframeRef} src={`/file/${encodeURIComponent(factoryPrintedLabelUrl)}#toolbar=0&navpanes=0&scrollbar=0`}
                        title="Shippo label" width="333.333" height="500" onLoad={this.autoPrintIframe.bind(this)}></iframe>
                    <Message positive>
                        <Message.Header>The shipping label should print automatically, if not <Button onClick={this.printIframe.bind(this)}>Click here...</Button></Message.Header>
                    </Message>
                </Grid.Column>
            </Grid>
        );
    }
}
