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

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

export default class ShopifyOrdersTable extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            orders: [],
            prevCursor: null,
            nextCursor: null,
            search: "",
            totalOrdersCount: 0
        };
    }

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

        return this.onLoadOrders();
    }

    async Refresh() {
        return this.onLoadOrders();
    }

    async onLoadOrders(cursor, search) {
        this.setState({ orders: [], loading: true });

        const queryString = new URLSearchParams();
        if (cursor) {
            queryString.append("cursor", cursor);
        }
        if (search) {
            queryString.append("search", search);
        }

        let url = `/api/admin/shop/shopify_orders`;

        if (queryString.size > 0) {
            url += `?${queryString.toString()}`;
        }

        const res = await superagent.get(url);

        const { orders, prevCursor, nextCursor, totalOrdersCount } = res.body;

        console.log(orders);

        this.setState({ orders, prevCursor, nextCursor, totalOrdersCount, loading: false });
    }

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

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

        if (shopifyOrder.origin === "TestData") {
            const res = await superagent.post(`/api/admin/shop/test_order`);
            window.location.href = `/shop/order/${res.body.id}`;
        } else {
            const res = await superagent.post(`/api/admin/shop/order`).send({
                shopifyOrderId: shopifyOrder.id
            });
            window.location.href = `/shop/order/${res.body.id}`;
        }
        this.setState({ loading: false });
    }

    render() {
        return (
            <BigOrdersWrapper title="Shopify Orders">
                {this.state.orders && <p>Total orders: {this.state.totalOrdersCount}</p>}
                <Form onSubmit={() => this.onLoadOrders(null, this.state.search)} loading={this.state.loading}>
                    <Form.Group inline>
                        <Form.Field>
                            {(this.state.nextCursor && this.state.prevCursor) && <Button type='button' icon onClick={async (e) => await this.onLoadOrders()}><Icon name='angle double left' /></Button>}
                            {this.state.prevCursor && <Button type='button' icon onClick={async (e) => this.onLoadOrders(this.state.prevCursor)}><Icon name='angle left' /></Button>}
                            <Button type='button' icon onClick={async (e) => { await this.onLoadOrders(this.state.currentCursor, this.state.search) }}><Icon name='refresh' /></Button>
                            {this.state.nextCursor && <Button type='button' icon onClick={async (e) => this.onLoadOrders(this.state.nextCursor)}><Icon name='angle right' /></Button>}
                        </Form.Field>
                        <Form.Field width={8}>
                            <Form.Input width={8} disabled={this.state.loading} autoComplete="off" icon="search" placeholder='Customer email or #OrderID...'
                                name="search" onChange={this.onChange.bind(this)} />
                            <Button primary type='submit'>Search</Button>
                        </Form.Field>
                    </Form.Group>
                </Form>
                <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>
                        {this.state.orders.map(orderPair => <ShopifyOrderTableRow key={orderPair.shopifyOrder.id} orderPair={orderPair} schemas={this.state.schemas} />)}
                    </Table.Body>
                </Table>
            </BigOrdersWrapper>
        )
    }
}
