import React from 'react';
import superagent from 'superagent';
import { fromUnixTime, formatDistanceToNow } from "date-fns";
import { formatInTimeZone } from 'date-fns-tz'
import constants, { DEFAULT_TIMEZONE } from '../CloudApi/Constants.js';

import { Icon, Button, Table, Message, Label, Flag, Image } from 'semantic-ui-react'

export default class ShopifyOrderTableRow extends React.Component {
    render() {
        const shopifyOrder = this.props.orderPair.shopifyOrder;

        const createdAtDateTime = Date.parse(shopifyOrder.created_at);
        const created = formatInTimeZone(createdAtDateTime, DEFAULT_TIMEZONE, 'PPp');

        const customerInfo = (shopifyOrder.customer) ? (
            <div>
                <p>{shopifyOrder.customer.first_name} {shopifyOrder.customer.last_name}</p>
                <p>Location: {shopifyOrder.customer_locale}</p>
            </div>
        ) : null;

        const identifiers = (shopifyOrder.id) ? (
            <div>
                <a style={{ textDecoration: "underline" }} href={`/shop/shopify/${shopifyOrder.id}`}>{shopifyOrder.name}</a>
            </div>
        ) : null;

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

        const verifiedEmail = (shopifyOrder.customer && shopifyOrder.customer.verified_email) ? (
            <Label>YES</Label>
        ) : null;

        const shippingInfo = (shopifyOrder.shipping_address) ? (
            <div>
                <p>{shopifyOrder.shipping_address.name}</p>
                <p>{shopifyOrder.shipping_address.city}, {shopifyOrder.shipping_address.province_code} {shopifyOrder.shipping_address.zip}</p>
                <p>{shopifyOrder.shipping_address.country}&nbsp;<Flag name={shopifyOrder.shipping_address.country_code.toLowerCase()} /></p>
            </div>
        ) : null;

        const itemsWithIpd = {};
        if (shopifyOrder.line_items) {
            for (const item of shopifyOrder.line_items) {
                if (item.properties) {
                    const ipd = item.properties.find(property => property.name === "IPD");
                    if (ipd) {
                        itemsWithIpd[item.id] = ipd.value;
                    }
                }
            }
        }

        const refundedLineItemIds = shopifyOrder.refunds.reduce((acc, refund) => {
            const ids = refund.refund_line_items.map(item => item.line_item_id);
            return [...acc, ...ids];
        }, []);
        
        // Unfulfilled line items
        const unfulfilledLineItems = shopifyOrder.line_items.filter(
            lineItem => lineItem.fulfillment_status !== "fulfilled" && lineItem.fulfillment_status !== "refunded" && !refundedLineItemIds.includes(lineItem.id)
        );

        const items = (shopifyOrder.line_items) ? (
            <div>
                {shopifyOrder.line_items.map(item => {
                    if (item.fulfillment_status === "fulfilled") {
                        return (<div><Label color="blue">Fulfilled</Label> {item.quantity}x <Label>{item.title} (SKU: {item.sku})</Label> {itemsWithIpd[item.id] && <Label color="blue">IPD: {itemsWithIpd[item.id]}</Label>}</div>);
                    } else if (item.fulfillment_status === "refunded" || refundedLineItemIds.includes(item.id)) {
                        return (<div><Label color="red">Refunded</Label> {item.quantity}x <Label>{item.title} (SKU: {item.sku})</Label> {itemsWithIpd[item.id] && <Label color="blue">IPD: {itemsWithIpd[item.id]}</Label>}</div>);
                    } else {
                        return (<div>{item.quantity}x <Label>{item.title} (SKU: {item.sku})</Label> {itemsWithIpd[item.id] && <Label color="blue">IPD: {itemsWithIpd[item.id]}</Label>}</div>);
                    }
                })}
            </div>
        ) : null;

        const compactLineItems = (shopifyOrder.line_items) ? (
            <div>
                {shopifyOrder.line_items.map(item => {
                    if (item.fulfillment_status === "fulfilled") {
                        return (<Label color="blue" size="tiny" horizontal>{item.quantity}x {item.title}{itemsWithIpd[item.id] && <Label color="blue">IPD: {itemsWithIpd[item.id]}</Label>}</Label>);
                    } else if (item.fulfillment_status === "refunded" || refundedLineItemIds.includes(item.id)) {
                        return null;
                    } else {
                        return (<Label size="tiny" horizontal>{item.quantity}x {item.title}</Label>);
                    }
                })}
            </div>
        ) : null;

        const tags = (shopifyOrder.tags) ? (
            <div>
                {shopifyOrder.tags.split(',').map(tag => (
                    <div><Label>{tag}</Label></div>
                ))}
            </div>
        ) : null;

        const origin = (shopifyOrder.origin && shopifyOrder.origin === "Shopify") ? (
            <a target="blank" href={`https://admin.shopify.com/store/bigscreenvr/orders/${this.props.orderPair.shopifyOrder.id}`}><Image size='tiny' src="/images/shopify_logo.png" /></a>
        ) : <span>Test Data</span>;

        const orderStatus = (shopifyOrder.financial_status) ? (
            <div>
                <div>Fulfillment Status: <Label>{shopifyOrder.fulfillment_status}</Label></div>
                <div>{
                    this.props.orderPair.bigOrder &&
                    <Button inverted color="green" size="tiny" href={`/shop/order/${this.props.orderPair.bigOrder.id}`}><Icon name='shopping bag' />View big order...</Button>
                }</div>
            </div>
        ) : null;

        const isBigOrder = this.props.orderPair.bigOrder && true;

        if (shopifyOrder.cancelled_at || !["paid", "partially_refunded"].includes(shopifyOrder.financial_status)) {
            return (
                <Table.Row disabled={false}>
                    <Table.Cell width={1} collapsing>{identifiers}</Table.Cell>
                    <Table.Cell colSpan={this.props.compact ? 2 : 6}><Label color="red">Shopify order is cancelled or refunded.</Label></Table.Cell>
                </Table.Row>
            )
        }

        if (this.props.compact) {
            return (
                <Table.Row disabled={false} positive={isBigOrder}>
                    <Table.Cell width={1} collapsing>{compactIdentifiers}</Table.Cell>
                    <Table.Cell width={1} collapsing>{customerInfo}</Table.Cell>
                    <Table.Cell width={1} collapsing>{compactLineItems}</Table.Cell>
                </Table.Row>
            )
        } else {
            return (
                <Table.Row disabled={false} positive={isBigOrder}>
                    <Table.Cell width={1} collapsing>{identifiers}</Table.Cell>
                    <Table.Cell width={1} collapsing>{created}</Table.Cell>
                    <Table.Cell width={1} collapsing>{shippingInfo}</Table.Cell>
                    <Table.Cell width={1} collapsing>{items}</Table.Cell>
                    <Table.Cell width={1} collapsing>{tags}</Table.Cell>
                    <Table.Cell width={1} collapsing>{origin}</Table.Cell>
                    <Table.Cell width={1} collapsing>{orderStatus}</Table.Cell>
                </Table.Row>
            )
        }
    }
}
