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

import * as ApiUtils from '../CloudApi/ApiUtils.js';
import constants, { DEFAULT_TIMEZONE } from '../CloudApi/Constants.js';

/**
 * Renders table cells for a BigOrder in a compact table row format.
 * This component contains all the rendering logic for displaying BigOrder data as table cells.
 */
export default class BigOrderTableCells extends React.Component {
    renderCompactTitle() {
        let urlOrderId = this.props.bigOrder.id;

        const title = (
            <a style={{ textDecoration: "underline" }} href={`/shop/order/${urlOrderId}`}>{this.props.bigOrder.shopifyOrderName}</a>
        );

        const ipdLabel = (this.props.bigOrder.ipd !== -1)
            ? <Label color="blue">{this.props.bigOrder.ipd}mm</Label>
            : null;

        return (
            <div>
                <p>{title}</p>
                <p>Priority: {this.props.bigOrder.priority} {ipdLabel}</p>
            </div>
        );
    }

    renderCompactIpd() {
        if (this.props.bigOrder.ipd === -1) {
            return <Label color="orange">IPD Not Set</Label>
        }

        return <Label color="blue">{this.props.bigOrder.ipd}mm</Label>
    }

    renderCompactShopifyId() {
        const shopifyOrder = this.props.shopifyOrder || this.props.bigOrder.shopifyOrderSnapshot;

        return (shopifyOrder) ? (
            <div>
                <p>Order Number: <strong>#{shopifyOrder.order_number}</strong></p>
                <p>Name: {shopifyOrder.name}</p>
            </div>
        ) : null;
    }

    renderCompactShopifyCustomerInfo() {
        const shopifyOrder = this.props.shopifyOrder || this.props.bigOrder.shopifyOrderSnapshot;

        let selection = null;
        if (!_.isEmpty(this.props.bigOrder.purpose)) {
            selection = constants.BigOrderPurposeOptions.find((option) => option.value === this.props.bigOrder.purpose);
        } else if (this.props.bigOrder.origin === "TestData") {
            selection = constants.BigOrderPurposeOptions.find((option) => option.value === "Just Testing");
        }

        let purpose = null;
        if (selection) {
            purpose = <Label horizontal color={selection.label.color}>{selection.text}</Label>
        }

        return (shopifyOrder.customer) ? (
            <div>
                <p><a style={{ textDecoration: "underline" }} href={`/account/${this.props.bigOrder.ownerBigscreenAccountId}`}>{shopifyOrder.customer.first_name} {shopifyOrder.customer.last_name}</a> {purpose}</p>
                <p>Location: {shopifyOrder.shipping_address && shopifyOrder.shipping_address.country}</p>
            </div>
        ) : null;
    }

    renderCompactShopifyLink() {
        const shopifyOrderId = this.props.bigOrder.shopifyOrderId;
        if (!shopifyOrderId) {
            return null;
        }

        return (
            <a href={`https://admin.shopify.com/store/bigscreenvr/orders/${shopifyOrderId}`} target="_blank" rel="noopener noreferrer">
                <Image size='tiny' src="/images/shopify_logo.png" />
            </a>
        );
    }

    renderCompactLineItems() {
        const lineItemsLabels = [];

        for (const currentLineItem of this.props.bigOrder.currentLineItems) {
            if (this.props.shipmentGroupId === currentLineItem.shipmentGroupId) {
                lineItemsLabels.push(<Label color="green" inverted size="tiny">{ApiUtils.splitUpperCamelCase(currentLineItem.type)}</Label>);
            } else {
                lineItemsLabels.push(<Label size="tiny">{ApiUtils.splitUpperCamelCase(currentLineItem.type)}</Label>);
            }

            if (lineItemsLabels.length == 2) {
                lineItemsLabels.push(<p />);
            }
        }

        return (
            <div>
                {lineItemsLabels}
            </div>
        );
    }

    renderCompactChecklistStatus() {
        if (this.props.loadingChecklist) {
            return (
                <Icon name='circle notched' loading />
            )
        } else if (this.props.bigOrder.checklistResult) {
            let nextActionText = this.props.bigOrder.checklistResult.nextAction;
            if (nextActionText === "Shipped") {
                return <Label size="small" color="green"><Icon name='checkmark' />Shipped</Label>
            }

            if (this.props.bigOrder.checklistResult.nextAction === "SendScanRequest") {
                nextActionText = "Send scan request email to customer";
            }

            if (nextActionText === "WaitingForInventory") {
                return <div>
                    <Label size="small" color="orange">MAYBE READY TO SHIP</Label><p />
                    <Label size="small">{nextActionText}</Label>
                </div>
            } else {
                return <div>
                    <Label size="small" color="red">NOT READY TO SHIP</Label><p />
                    <Label size="small">{nextActionText}</Label>
                </div>
            }
        }
    }

    renderCompactCreatedAt() {
        const createdAtDateTime = Date.parse(this.props.bigOrder.shopifyOrderSnapshot.created_at);
        const createdAt = formatInTimeZone(createdAtDateTime, DEFAULT_TIMEZONE, 'PPp z');

        return (
            <p>{createdAt}</p>
        );
    }

    renderCompactUpdatedAt() {
        const updatedDateTime = fromUnixTime(Math.floor(_.last(this.props.bigOrder.history).createdAt / 1000));
        const updated = formatInTimeZone(updatedDateTime, DEFAULT_TIMEZONE, 'PPp');
        return (
            <p>{updated}</p>
        );
    }

    render() {
        if (!this.props.bigOrder) {
            return null;
        }

        if (this.props.bigOrder.state === "Cancelled") {
            return (
                <>
                    <Table.Cell collapsing width={2}>{this.renderCompactTitle()}</Table.Cell>
                    <Table.Cell disabled collapsing width={1}>{this.renderCompactCreatedAt()}</Table.Cell>
                    <Table.Cell disabled collapsing width={1}>{this.renderCompactUpdatedAt()}</Table.Cell>
                    <Table.Cell disabled collapsing>{this.renderCompactShopifyCustomerInfo()}</Table.Cell>
                    <Table.Cell disabled collapsing>{this.renderCompactShopifyLink()}</Table.Cell>
                    <Table.Cell disabled collapsing width={1} colspan='3'><Label color="orange">This order was cancelled</Label></Table.Cell>
                </>
            );
        } else {
            return (
                <>
                    <Table.Cell collapsing width={2}>{this.renderCompactTitle()}</Table.Cell>
                    <Table.Cell collapsing width={1}>{this.renderCompactCreatedAt()}</Table.Cell>
                    <Table.Cell collapsing width={1}>{this.renderCompactUpdatedAt()}</Table.Cell>
                    <Table.Cell collapsing>{this.renderCompactShopifyCustomerInfo()}</Table.Cell>
                    <Table.Cell collapsing>{this.renderCompactShopifyLink()}</Table.Cell>
                    <Table.Cell collapsing width={2}>{this.renderCompactLineItems()}</Table.Cell>
                    <Table.Cell collapsing width={1}>{this.renderCompactChecklistStatus()}</Table.Cell>
                </>
            );
        }
    }
}
