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 * as ApiUtils from '../CloudApi/ApiUtils.js';
import ApiButtonModal from '../CloudApi/ApiButtonModal.jsx';
import { Segment, Modal, Header, Icon, Button, Table, Form, Divider, Label, Message, Radio } from 'semantic-ui-react'
import ShopifyOrderTableRow from './ShopifyOrderTableRow.jsx';
import BigApiErrorMessage from '../CloudApi/BigApiErrorMessage.jsx';

export default class ShopifyOrderComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            scanRequestAction: "Unknown",
            error: null
        };
    }

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

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

        try {
            if (this.props.shopifyOrder.origin === "TestData") {
                const res = await superagent.post(`/api/admin/shop/test_order`);
                window.location.href = `/shop/order/${res.body.id}`;
            } else {
                const payload = {
                    shopifyOrderId: this.props.shopifyOrder.id
                };
    
                if (this.state.scanRequestAction === "DuplicateMostRecentScanRequest") {
                    payload.scanRequestAction = "DuplicateMostRecentScanRequest";
                }
    
                const res = await superagent.post(`/api/admin/shop/order`).send(payload).accept('json');
                window.location.href = `/shop/order/${res.body.id}`;
            }
        } catch (e) {
            this.setState({ error: e });
        }
        

        this.setState({ loading: false });
    }

    render() {
        if (!this.props.schemas) {
            return (
                <Segment basic loading={true} />
            );
        }

        if (!this.props.shopifyOrder) {
            return (
                <Segment basic loading={true} />
            );
        }

        const shopifyOrder = this.props.shopifyOrder;
        const bigOrder = this.props.bigOrder;

        console.log(shopifyOrder);

        let bigOrderButton;
        if (shopifyOrder.cancelled_at || !["paid", "partially_refunded"].includes(shopifyOrder.financial_status)) {
            bigOrderButton = null;
        } else if (!bigOrder) {
            let showScanRequestOption = false;
            if (this.props.products) {
                // Find a matching variant in the products list where the variant id is the same as the shopify order line item id
                this.props.products.forEach(product => {
                    product.variants.forEach(variant => {
                        if (shopifyOrder.line_items.find(item => item.variant_id === variant.id)) {
                            console.log(`Found matching variant ${variant.id} for shopify order line item ${shopifyOrder.line_items.find(item => item.variant_id === variant.id).id}`);
                            showScanRequestOption = true;
                        }
                    });
                });
            } else {
                const scanRequestSkus = [
                    "BS1FR",
                    "BS1B00",
                    "BS1F",
                    "RBS1F",
                    "BSBAPC"
                ];
    
                // Set this to true if the shopify order has any line item where sku is 
                showScanRequestOption = shopifyOrder.line_items.find(item => scanRequestSkus.includes(item.sku)) !== undefined;
            }

            bigOrderButton = (
                <ApiButtonModal key={shopifyOrder.id} color="blue" size="huge" text={`📦 Convert ${shopifyOrder.name} to a BigOrder`} cancel modalButtonText="📦 OK, Convert to a Big Order" hideOnError={false} onConfirm={this.onConvertToBigOrder.bind(this)}>
                    <Message warning icon>
                        <Icon name="warning" />
                        <Message.Content>
                            <Message.Header>Warning</Message.Header>
                            This action can not be undone!
                        </Message.Content>
                    </Message>


                    {showScanRequestOption &&
                        <Segment>
                            <Header>Scan Request Action</Header>
                            <Form>
                                <Form.Group>
                                    <Radio toggle
                                        label={"Copy the customer\'s most recent successful scan request to this order"}
                                        name='scanRequestAction'
                                        value={this.props.schemas.BigOrderScanRequestActions["DuplicateMostRecentScanRequest"]}
                                        checked={this.state.scanRequestAction === this.props.schemas.BigOrderScanRequestActions["DuplicateMostRecentScanRequest"]}
                                        onChange={this.onChange.bind(this)}
                                    />
                                </Form.Group>

                                <Form.Group>
                                    <Radio toggle
                                        label='Create a new scan request for this order'
                                        name='scanRequestAction'
                                        value={this.props.schemas.BigOrderScanRequestActions["CreateNewScanRequest"]}
                                        checked={this.state.scanRequestAction === this.props.schemas.BigOrderScanRequestActions["CreateNewScanRequest"]}
                                        onChange={this.onChange.bind(this)}
                                    />
                                </Form.Group>
                            </Form>
                        </Segment>
                    }
                </ApiButtonModal>
            )
        }

        if (this.props.compact) {
            return (
                <Table size='tiny' compact singleLine>
                    <Table.Header>
                        <Table.Row>
                            <Table.HeaderCell collapsing>ID</Table.HeaderCell>
                            <Table.HeaderCell collapsing>Customer Info</Table.HeaderCell>
                            <Table.HeaderCell collapsing>Items</Table.HeaderCell>
                        </Table.Row>
                    </Table.Header>
                    <Table.Body>
                        <ShopifyOrderTableRow compact={true} key={shopifyOrder.id} orderPair={{ shopifyOrder, bigOrder }} schemas={this.props.schemas} />

                    </Table.Body>
                </Table>
            )
        } else {
            return (
                <>
                    <Table celled compact>
                        <Table.Header>
                            <Table.Row>
                                <Table.HeaderCell collapsing>ID</Table.HeaderCell>
                                <Table.HeaderCell collapsing>Created (PDT)</Table.HeaderCell>
                                <Table.HeaderCell collapsing>Shipping Info</Table.HeaderCell>
                                <Table.HeaderCell collapsing>Items</Table.HeaderCell>
                                <Table.HeaderCell collapsing>Tags</Table.HeaderCell>
                                <Table.HeaderCell collapsing>Origin</Table.HeaderCell>
                                <Table.HeaderCell collapsing>Status</Table.HeaderCell>
                            </Table.Row>
                        </Table.Header>
                        <Table.Body>
                            <ShopifyOrderTableRow key={shopifyOrder.id} orderPair={{ shopifyOrder, bigOrder }} schemas={this.props.schemas} />
                        </Table.Body>
                    </Table>
                    {this.state.error && <BigApiErrorMessage error={this.state.error} />}
                    {bigOrderButton}
                </>
            )
        }
    }
}
