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 ShopifyOrderComponent from './ShopifyOrderComponent.jsx';
import BigOrdersWrapper from './BigOrdersWrapper.jsx';

import { Segment, Modal, Header, Icon, Button, Table, Form, Message, Radio } from 'semantic-ui-react'

export default class ShopifyHome extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            shopifyOrder: null,
            bigOrder: undefined,
        };
    }

    async componentDidMount() {
        this.setState({ loading: true });
        let schemas = await ApiUtils.getFabricatorSchemas();
        this.setState({ schemas });

        let res = await superagent.get(`/api/admin/shop/shopify_order/${this.props.match.params.shopifyOrderId}`);
        let shopifyOrder = res.body;
        this.setState({ shopifyOrder });

        let res2 = await superagent.get(`/api/admin/shop/orders?shopifyOrderId=${shopifyOrder.id}`);
        if (res2.body.items && res2.body.items.length > 0) {
            this.setState({ bigOrder: res2.body.items[0] });
        }

        /*
        try { 
            let res3 = await superagent.get(`/api/admin/fabricator /products`);
            let products = res3.body.items;
            this.setState({ products });
        } catch (e) {
            console.error(e);
        }*/

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

    render() {
        if (!this.state.shopifyOrder || this.state.loading) {
            return (
                <BigOrdersWrapper title="Shopify Order">
                    <Segment basic loading={this.state.loading} />
                </BigOrdersWrapper>
            );
        }

        return (
            <BigOrdersWrapper title={`Shopify Order ${this.state.shopifyOrder.name}`}>
                <ShopifyOrderComponent schemas={this.state.schemas} shopifyOrder={this.state.shopifyOrder} bigOrder={this.state.bigOrder} />
                {this.state.bigOrder &&
                    <Button color="green" href={`/shop/order/${this.state.bigOrder.id}`}><Icon name='arrow right' />&nbsp;View BigOrder status...</Button>
                }
            </BigOrdersWrapper>
        )
    }
}
