import React from 'react';
import superagent from 'superagent';
import cookie from 'react-cookies';

import constants, { DEFAULT_TIMEZONE } from '../CloudApi/Constants.js';
import { Segment, Form, Button, Icon, Pagination } from 'semantic-ui-react';
import { DateInput } from 'semantic-ui-calendar-react';

import * as ApiUtils from '../CloudApi/ApiUtils.js';
import BigOrdersWrapper from './BigOrdersWrapper.jsx';
import BigOrderTable from './BigOrderTable.jsx';
import BigApiErrorMessage from '../CloudApi/BigApiErrorMessage.jsx';
import BigOrdersQuery from './BigOrdersQuery.jsx';

export default class BigOrderList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            currentPageIndex: 1,
            pageCount: 0,
            items: [],
            query: {
                origin: "Shopify"
            },
            count: 0,
            limit: 50,
        };
    }

    async componentDidMount() {
        try {
            let schemas = await ApiUtils.getFabricatorSchemas();
            this.setState({ schemas });
        } catch (e) {
            console.log(e);
        }
    }

    async onUpdateQuery(params) {
        this.setState({ loading: true, count: undefined });
        try {
            console.log("Querying", params.toString());
            const res = await superagent.get(`/api/admin/shop/orders?${params.toString()}`);
            const pageCount = Math.ceil(res.body.count / this.state.limit);
            this.setState({ items: res.body.items, count: res.body.count, pageCount });
        } catch (e) {
            this.setState({ error: e });
        }
        this.setState({ loading: false });
    }

    // newPageIndex is 1-based
    async onPageChanged(newPageIndex) {
        this.setState({ currentPageIndex: newPageIndex, offset: Math.max(newPageIndex - 1, 0) * this.state.limit }, async () => {
            const params = new URLSearchParams(window.location.search);
            // Fixes: https://github.com/BigscreenVR/bugs/issues/1203
            params.set("offset", this.state.offset);
            params.set("limit", this.state.limit);
            await this.onUpdateQuery(params);
        });
    }

    render() {
        if (!this.state.schemas) return null;

        const pagination = (
            <div style={{ display: "flex", alignItems: "center" }}>
                <div style={{ flex: 0 }}>
                    <Pagination
                        disabled={this.state.pageCount <= 1}
                        activePage={this.state.currentPageIndex}
                        onPageChange={async (e, { activePage }) => this.onPageChanged(activePage)}
                        totalPages={this.state.pageCount}
                        ellipsisItem={true}
                        firstItem={true}
                        lastItem={true}
                    />
                </div>
                <div style={{ flex: 1, textAlign: "left", alignItems: "center", marginLeft: "1em" }}>
                    {this.state.items && <p>{this.state.count} items found</p>}
                </div>
            </div>
        );

        return (
            <BigOrdersWrapper title={`📦 Big Orders (${this.state.count})`}>
                <BigApiErrorMessage error={this.state.error} />

                <BigOrdersQuery schemas={this.state.schemas} onQueryUpdated={this.onUpdateQuery.bind(this)} loading={this.state.loading} />

                {pagination}
                <BigOrderTable schemas={this.state.schemas} loading={this.state.loading} orders={this.state.items} showDetail={false} />
                {pagination}
            </BigOrdersWrapper>
        );
    }
}
