import React from 'react';
import superagent from 'superagent';
import { fromUnixTime, formatDistanceToNow } from "date-fns";
import { formatInTimeZone } from 'date-fns-tz';
import { Segment, Form, Table, Statistic, Label, Button, Icon, Pagination, Header } from 'semantic-ui-react'
import { DateInput } from 'semantic-ui-calendar-react';

import constants, { DEFAULT_TIMEZONE } from '../CloudApi/Constants.js';
import * as ApiUtils from '../CloudApi/ApiUtils.js';
import InventoryWrapper from './InventoryWrapper.jsx';
import InventoryItemsTable from './InventoryItemsTable.jsx';
import HandScannerInput from '../Util/HandScannerInput.jsx';

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

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

            const params = new URLSearchParams(window.location.search);
            const query = {};
            for (const [key, value] of params.entries()) {
                if (key === "limit") {
                    this.setState({ limit: value });
                } else if (key === "offset") {
                    this.setState({ offset: value });
                } else if (key === "minCreatedAt") {
                    query["minCreatedAt"] = new Date(parseInt(value)).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
                } else if (key === "maxCreatedAt") {
                    query["maxCreatedAt"] = new Date(parseInt(value)).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
                } else {
                    query[key] = value;
                }
            }
            console.log(query);
            this.setState({ query });

            await this.onUpdateQuery();
        } catch (e) {
            console.log(e);
        }

        let res2 = await superagent.get(`/api/admin/inventory/stats`);
        this.setState({ stats: res2.body });
    }

    async onSerialNumberScanned(scannedSerialNumber) {
        return this.onChange(null, { name: "serialNumberLike", value: scannedSerialNumber });
    }

    onChange(e, { name, value }) {
        const query = this.state.query;

        if (_.isEmpty(value)) {
            console.log("delete", name, value);
            delete query[name];
        } else {
            if (name === "state" && value === ApiUtils.ANY_VALUE) {
                delete query["state"];
            } else if (name === "shopifyMinCreatedAt") {
                query["minCreatedAt"] = new Date(value).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
                // console.log("minCreatedAt", query["minCreatedAt"]); //debug
            } else if (name === "shopifyMaxCreatedAt" && !_.isEmpty(value)) {
                query["maxCreatedAt"] = new Date(value).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
            } else {
                query[name] = value;
            }
        }

        this.setState({ query }, async () => {
            const params = this.getUrlSearchParams();
            console.log('onChange query setState', params.toString());
            const newPathQuery = `${window.location.pathname}?${params.toString()}`;
            window.history.pushState(null, '', newPathQuery);
            await this.onUpdateQuery();
        });
    }

    getUrlSearchParams() {
        const queryString = new URLSearchParams();
        queryString.append("limit", this.state.limit);
        queryString.append("offset", this.state.offset);

        console.log("getUrlSearchParams", Object.entries(this.state.query))

        if (this.state.query) {
            for (const [key, value] of Object.entries(this.state.query)) {
                if (value === "" || value === null) continue;
                if (key.includes("CreatedAt")) {
                    queryString.append(key, new Date(value).getTime());
                } else {
                    queryString.append(key, value);
                }
            }
        }

        return queryString;
    }

    async onUpdateQuery() {
        try {
            this.setState({ loading: true });
            const params = this.getUrlSearchParams();
            const res = await superagent.get(`/api/admin/inventory/items?${params.toString()}`);
            const pageCount = Math.ceil(res.body.count / this.state.limit);
            console.log(res.body);
            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 }, () => {
            this.onUpdateQuery(0);
        });
    }

    render() {
        if (!this.state.schemas) {
            return <div />;
        }
        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 firstItem lastItem />
                </div>
                <div style={{ flex: 1, textAlign: "left", alignItems: "center", marginLeft: "1em" }}>
                    {this.state.items && <p>{this.state.count} items found</p>}
                </div>
            </div>
        );

        return (
            <InventoryWrapper title="Inventory">
                <Header as="h3">Inventory Items In Stock:</Header>
                <Statistic.Group size="small">
                    {this.state.stats && this.state.stats.statsByTypeInStock.map((stat, index) => {
                        if (stat.count <= 5) {
                            return null;
                        }
                        return <Statistic>
                            <Statistic.Value>
                                {stat.count}</Statistic.Value>
                            <Statistic.Label>{ApiUtils.splitUpperCamelCase(stat.type)}</Statistic.Label>
                        </Statistic>
                    })}
                </Statistic.Group>
                {this.state.schemas && <Segment secondary>
                    <Form size="small" onSubmit={this.onChange.bind(this)}>
                        <Form.Group>
                            <DateInput
                                name="minCreatedAt"
                                width={2}
                                size="small"
                                autoComplete="off"
                                dateFormat='LL'
                                clearable
                                closable
                                inlineLabel
                                label="From"
                                placeholder="Created After"
                                value={this.state.query.minCreatedAt}
                                iconPosition="left"
                                onChange={this.onChange.bind(this)} />
                            <DateInput
                                name="maxCreatedAt"
                                width={2}
                                size="small"
                                autoComplete="off"
                                dateFormat='LL'
                                clearable
                                closable
                                inlineLabel
                                label="To"
                                placeholder="Create Before"
                                value={this.state.query.maxCreatedAt}
                                iconPosition="left"
                                onChange={this.onChange.bind(this)} />
                            <Form.Select
                                inline
                                label='Status'
                                name="status"
                                clearable
                                value={this.state.query.status}
                                options={this.state.schemas.InventoryItemStatusOptions}
                                onChange={this.onChange.bind(this)}
                            />
                            <Form.Select
                                inline
                                label='Type'
                                name="type"
                                clearable
                                value={this.state.query.type}
                                options={this.state.schemas.BigProductTypeOptions}
                                onChange={this.onChange.bind(this)}
                            />
                        </Form.Group>
                        <Form.Group>
                            <HandScannerInput value={this.state.query.serialNumber} inlineFormInput label="Serial&nbsp;Number" icon="barcode" onScanFinished={this.onSerialNumberScanned.bind(this)} />
                        </Form.Group>
                    </Form>
                </Segment>}

                {!this.state.loading && this.state.count > 0 && pagination}
                {this.state.count > 0 && <InventoryItemsTable schemas={this.state.schemas} inventoryItems={this.state.items} count={this.state.count} loading={this.state.loading} />}
                {this.state.loading && <Segment basic loading={this.state.loading} />}
                {!this.state.loading && this.state.count === 0 && <div>Nothing found.</div>}
                {!this.state.loading && this.state.count > 0 && pagination}
            </InventoryWrapper>
        );
    }
}
