import React, { useRef } from 'react';
import superagent from 'superagent';
import { Message, Segment, Grid, Header, Icon, Button, Table, Form, Divider, Label, Transition } from 'semantic-ui-react'

import * as ApiUtils from '../CloudApi/ApiUtils.js';
import BigApiErrorMessage from '../CloudApi/BigApiErrorMessage.jsx';
import HandScannerInput from '../Util/HandScannerInput.jsx';
import InventoryWrapper from './InventoryWrapper.jsx';
import InventoryItemComponent from './InventoryItemComponent.jsx';

export default class InventoryScanIngest extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            savedQueries: [],
            newItemSerialNumber: "",
            scannedSerialNumber: "",
            shiftKeyPressed: false,
            autoCreateItems: true,
            error: null
        };
    }

    async componentDidMount() {
        this.setState({ menuLoading: true });

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

    async onScannedSerialNumberFinished(scannedSerialNumber) {
        if (scannedSerialNumber.startsWith("bs")) {
            scannedSerialNumber = scannedSerialNumber.toUpperCase();
        }

        this.setState({ loading: true, scannedSerialNumber: "", error: null });

        try {
            this.setState({ message: null, loading: true, newItemSerialNumber: "", scannedSerialNumber: "", items: [], createdInventoryItem: null });
            const res = await superagent.get(`/api/admin/inventory/items?serialNumber=${scannedSerialNumber}`);
            this.setState({ items: res.body.items, menuLoading: false });

            if (res.body.items.length === 0) {
                const res2 = await superagent.get(`/api/admin/inventory/hint?serialNumber=${scannedSerialNumber}`);
                console.log(res2.body);

                if (res2.body.hint === "Unknown") {
                    this.setState({ error: "Unrecognised serial number: " + scannedSerialNumber });
                    const audio = new Audio("/misc/Error1.wav");
                    audio.play();
                } else {
                    this.setState({ hint: res2.body.hint, newItemSerialNumber: scannedSerialNumber, loading: false });
                    if (this.state.autoCreateItems) {
                        setTimeout(this.onCreateBigInventoryItem.bind(this), 1000);
                    }
                }
            } else {
                const audio = new Audio("/misc/Alert1.wav");
                audio.play();
            }
        } catch (ex) {
            this.setState({ error: ex });
            console.error(ex);
        }

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

    async onCreateBigInventoryItem() {
        try {
            const res = await superagent.post(`/api/admin/inventory/item`).send({
                serialNumber: this.state.newItemSerialNumber
            });
            this.setState({ createdInventoryItem: res.body });

            setTimeout(this.onDismissMessage.bind(this), 4000);

            const audio = new Audio("/misc/Notification3_2.wav");
            audio.play();
        } catch (e) {
            console.log(e);
            this.setState({ error: ex.response });
        }

        this.setState({ loading: false, newItemSerialNumber: "" });
    }

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

    onIngestInventoryItem(e) {
        e.preventDefault();
    }

    onDismissMessage(e) {
        this.setState({ message: null });
    }

    renderInventoryItems(inventoryItems) {
        return (<Table celled>
            <Table.Header>
                <Table.Row>
                    <Table.HeaderCell>Serial Number</Table.HeaderCell>
                    <Table.HeaderCell>ID</Table.HeaderCell>
                    <Table.HeaderCell>Item Type</Table.HeaderCell>
                    <Table.HeaderCell>Item Status</Table.HeaderCell>
                </Table.Row>
            </Table.Header>

            <Table.Body>
                {inventoryItems.map((item, index) => {
                    return <Table.Row key={index}>
                        <Table.Cell><a style={{ textDecoration: "underline" }} href={`/inventory/item/${item.id}`}>{item.serialNumber}</a></Table.Cell>
                        <Table.Cell><a href={`/inventory/item/${item.id}`}>{item.id}</a></Table.Cell>
                        <Table.Cell><Label>{ApiUtils.splitUpperCamelCase(item.type)}</Label></Table.Cell>
                        <Table.Cell>{item.status}</Table.Cell>
                    </Table.Row>
                })}
            </Table.Body>
        </Table>)
    }

    render() {
        let scannedItem = null;
        let createNewButton = null;
        let autoCreateInfo = null;
        if (this.state.newItemSerialNumber && this.state.newItemSerialNumber.length > 0) {
            createNewButton = (
                <Segment>
                    <Message error icon>
                        <Icon name='warning' />
                        <Message.Content>
                            <Message.Header>Not found</Message.Header>
                            There is no item with this serial number in the database. You can create a new item with this serial number.
                        </Message.Content>
                    </Message>
                    <Header as="h3">Creating a new inventory item...</Header>
                    <Header as="h4">Serial Number: {this.state.newItemSerialNumber}</Header>
                    <Header as="h4">Expected type: {this.state.hint}</Header>
                    <Button fluid primary content='Create a new item' type='submit' onClick={this.onCreateBigInventoryItem.bind(this)} />
                </Segment>
            );

            autoCreateInfo = <Segment>
                <Message warning icon>
                    <Icon name='circle notched' loading />
                    <Message.Content>
                        <Message.Header>Not found</Message.Header>
                        There is no item with this serial number in the database. Automatically creating it...
                    </Message.Content>
                </Message>
                <Header as="h3">Automatically creating a new inventory item...</Header>
                <Header as="h4">Serial Number: {this.state.newItemSerialNumber}</Header>
                <Header as="h4">Expected type: {this.state.hint}</Header>
            </Segment>
        }

        if (this.state.items && this.state.items.length > 0) {
            scannedItem = <div>
                <Message positive icon>
                    <Icon name='check' />
                    <Message.Content>
                        <Message.Header>Item exists!</Message.Header>
                        This item already exists in the inventory.
                    </Message.Content>
                </Message>
                {this.renderInventoryItems(this.state.items)}
            </div>;
        }

        if (this.state.createdInventoryItem) {
            scannedItem = <div>
                <Message positive icon>
                    <Icon name='check' />
                    <Message.Content>
                        <Message.Header>Created!</Message.Header>
                    </Message.Content>
                </Message>
                {this.renderInventoryItems([this.state.createdInventoryItem])}
            </div>;
        }

        return (
            <InventoryWrapper title="Inventory Ingest">
                <HandScannerInput type="inventory" onScanFinished={this.onScannedSerialNumberFinished.bind(this)} />
                <Segment basic loading={this.state.loading}>
                    {this.state.message && <Message onDismiss={this.onDismissMessage.bind(this)} positive>{this.state.message}</Message>}
                    <BigApiErrorMessage error={this.state.error} />
                    <Transition visible={!this.state.loading} animation='fade' duration={500}>
                        <div>
                            {scannedItem}
                            {!this.state.autoCreateItems && createNewButton}
                            {this.state.autoCreateItems && autoCreateInfo}
                        </div>
                    </Transition>
                </Segment>
            </InventoryWrapper>
        );
    }
}
