import React from 'react';
import superagent from 'superagent';
import cookie from 'react-cookies';
import { Message } from 'semantic-ui-react';

import * as ApiUtils from '../CloudApi/ApiUtils.js';
import BigOrdersWrapper from './BigOrdersWrapper.jsx';
import BigOrderComponent from './BigOrderComponent.jsx';

export default class BigOrderHome extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            bigOrder: null,
            shipments: [],
            warning: null
        };
    }

    async componentDidMount() {
        // Check for warning query parameter from order creation
        const urlParams = new URLSearchParams(window.location.search);
        const warning = urlParams.get('warning');
        if (warning) {
            this.setState({ warning: decodeURIComponent(warning) });
        }
        await this.reloadbigOrder();
    }

    async reloadbigOrder() {
        let bigOrderId;
        try {
            let schemas = await ApiUtils.getFabricatorSchemas();
            this.setState({ schemas });

            let hash = window.location.hash;
            let bigOrderSearchId;
            if (hash) {
                bigOrderSearchId = hash;
            } else {
                bigOrderSearchId = this.props.match.params.bigOrderId;
            }

            if (bigOrderSearchId.startsWith("#BS")) {
                bigOrderSearchId = encodeURIComponent(bigOrderSearchId);
                const res = await superagent.get(`/api/admin/shop/orders?limit=1&shopifyOrderName=${bigOrderSearchId}`).accept('json');
                if (res.body.items.length === 1) {
                    bigOrderId = res.body.items[0].id;
                    this.setState({ bigOrder: res.body.items[0] });
                    console.log(res.body);
                } else {
                    this.setState({ bigOrder: null });
                }
            } else {
                const res = await superagent.get(`/api/admin/shop/order/${bigOrderSearchId}`).accept('json');
                bigOrderId = res.body.id;
                this.setState({ bigOrder: res.body });
                console.log(res.body);
            }

            const scanRequestsRes = await superagent.get(`/api/admin/shop/order/${bigOrderId}/scan_requests`).accept('json');
            console.log(scanRequestsRes.body);
            this.setState({ scanRequests: scanRequestsRes.body.items });

        } catch (e) {
            console.log(e);
        }

        try {
            const res2 = await superagent.get(`/api/admin/shipper/shipments?bigOrderId=${bigOrderId}`).accept('json');
            console.log(res2.body);
            this.setState({ shipments: res2.body.items });
        } catch (e) {
            console.log(e);
        }

        try {
            let res = await superagent.get(`/api/admin/shop/shopify_order/${this.state.bigOrder.shopifyOrderId}`);
            this.setState({ shopifyOrder: res.body });
        } catch (e) {
            console.error("Shopify order not found, using snapshot");
            if (this.state.bigOrder.shopifyOrderSnapshot) {
                const shopifyOrder = this.state.bigOrder.shopifyOrderSnapshot;
                shopifyOrder.THIS_SHOPIFY_ORDER_WAS_DELETED = 1;
                this.setState({ shopifyOrder });
            }
        }

        try {
            let res = await superagent.get(`/api/admin/shop/products`);
            this.setState({ products: res.body });
        } catch (e) {
            console.log(e);
        }
    }

    render() {
        if (this.state.bigOrder) {
            return (
                <BigOrdersWrapper loading={false}>
                    {this.state.warning && (
                        <Message warning>
                            <Message.Header>Order created with warnings</Message.Header>
                            <p>{this.state.warning}</p>
                        </Message>
                    )}
                    <BigOrderComponent schemas={this.state.schemas} bigOrder={this.state.bigOrder} shopifyOrder={this.state.shopifyOrder} scanRequests={this.state.scanRequests} shipments={this.state.shipments} products={this.state.products} showDetail={true} />
                </BigOrdersWrapper>
            );
        } else {
            return null;
        }
    }
}
