import React, { useRef, useEffect } from 'react';
import superagent from 'superagent';
import { fromUnixTime, formatDistanceToNow } from "date-fns";
import { formatInTimeZone } from 'date-fns-tz';

import * as ApiUtils from '../CloudApi/ApiUtils.js';
import ApiButtonModal from '../CloudApi/ApiButtonModal.jsx';
import constants, { DEFAULT_TIMEZONE } from '../CloudApi/Constants.js';
import { Header, Message, Icon, Button, Table, Label, Modal, Segment, Form } from 'semantic-ui-react'
import InventoryItemPickingHint from './InventoryItemPickingHint.jsx';

export default class InventoryItemComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            deleteInventoryItemModalOpen: false,
        };
    }

    showDeleteInventoryItemModal() { }

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

    openForceDeleteInventoryItemModal(i, e) {
        this.setState({ deleteInventoryItemModalOpen: true, force: true });
    }

    openDeleteInventoryItemModal(i, e) {
        this.setState({ deleteInventoryItemModalOpen: true, force: false });
    }

    closeDeleteInventoryItemModal(i, e) {
        this.setState({ deleteInventoryItemModalOpen: false });
    }

    async onCancelInventoryItem(e) {
        e.preventDefault();
        this.setState({ loading: true });
        try {
            let url = `/api/admin/inventory/item/${this.props.inventoryItem.id}`;
            let res = await superagent.delete(url);
            window.location.reload();
        } catch (e) {
            window.alert("Error deleting: " + e.message);
            console.error(e);
        }

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

    async onAdjustQuantity() {
        try {
            let url = `/api/admin/inventory/item/${this.props.inventoryItem.id}`;
            let res = await superagent.put(url).send({
                quantity: this.state.newQuantity
            });
            window.location.reload();
        } catch (e) {
            window.alert("Error adjusting quantity: " + e.message);
            console.error(e);
        }
    }

    async onDeleteInventoryItem() {
        this.setState({ loading: true });
        try {
            let url = `/api/admin/inventory/item/${this.props.inventoryItem.id}?force=1`;
            let res = await superagent.delete(url);
            window.location.reload();
        } catch (e) {
            window.alert("Error deleting: " + e.message);
            console.error(e);
        }

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

    render() {
        if (this.state.loading) {
            return (
                <div />
            )
        }

        let createdAtDateTime = fromUnixTime(this.props.inventoryItem.createdAt / 1000);
        const createdAt = formatInTimeZone(createdAtDateTime, DEFAULT_TIMEZONE, 'PPPp z');
        const fromNow = formatDistanceToNow(createdAtDateTime, { addSuffix: true });

        const history = this.props.history && this.props.history.map((historyItem, historyItemIndex) => {
            let createdAtDateTime = fromUnixTime(historyItem.createdAt / 1000);
            const createdAt = formatInTimeZone(createdAtDateTime, DEFAULT_TIMEZONE, 'PPPp z');
            return (<Table.Row key={historyItemIndex}>
                <Table.Cell width={2}>
                    {createdAt}
                </Table.Cell>
                <Table.Cell width={2}>
                    {historyItem.creatorBigscreenAccountId || '—'}
                </Table.Cell>
                <Table.Cell>
                    {historyItem.message}
                    {(historyItem.metadata && historyItem.metadata.reason) && <div><strong>Reason:</strong> {historyItem.metadata.reason}</div>}
                    {(historyItem.metadata && historyItem.metadata.bigShipmentId) && <div><a href={`/shipper/shipment/${historyItem.metadata.bigShipmentId}`}>View Shipment</a></div>}
                </Table.Cell>
            </Table.Row>)
        });

        const inventoryItemState = Object.entries(this.props.schemas.InventoryItemStatuses).find(entry => entry[1] === this.props.inventoryItem.status)[0];
        const stateLabelColor = (this.props.inventoryItem.status === this.props.schemas.InventoryItemStatuses["VerifiedAndReady"]) ? "green" : "grey";

        const header = (
            <Table.Header fullWidth>
                <Table.Row>
                    <Table.HeaderCell colSpan='2'>
                        <ApiButtonModal color="red" size="small" text="Cancel this inventory item" cancel modalIcon="user cancel" modalButtonText="OK, cancel this inventory item" onConfirm={this.onCancelInventoryItem.bind(this)}>
                            Are you sure you want to cancel this inventory item?
                        </ApiButtonModal>
                    </Table.HeaderCell>
                </Table.Row>
            </Table.Header>
        );

        return (
            <div>
                {(this.props.inventoryItem.trackingType && this.props.inventoryItem.trackingType === 'QuantityTracked') && 
                    <Segment inverted color="blue">This is a quantity tracked item with {this.props.inventoryItem.quantity} items in stock</Segment>
                }
                <Table compact singleLine loading={this.state.loading}>
                    <Table.Body>
                        <Table.Row>
                            <Table.HeaderCell width={3}>Type</Table.HeaderCell>
                            <Table.Cell><Label>{ApiUtils.splitUpperCamelCase(this.props.inventoryItem.type)}</Label> </Table.Cell>
                        </Table.Row>

                        <Table.Row>
                            <Table.HeaderCell width={3}>Serial number</Table.HeaderCell>
                            <Table.Cell>{this.props.inventoryItem.serialNumber}&nbsp;<Button size="tiny" onClick={() => { navigator.clipboard.writeText(this.props.inventoryItem.serialNumber) }}>Copy</Button></Table.Cell>
                        </Table.Row>

                        {(this.props.inventoryItem.trackingType && this.props.inventoryItem.trackingType === 'QuantityTracked') && <Table.Row>
                            <Table.HeaderCell width={3}>Quantity</Table.HeaderCell>
                            <Table.Cell>{this.props.inventoryItem.quantity}<br />
                                <ApiButtonModal color="blue" size="tiny" text="Adjust quantity" modalIcon="edit" modalButtonText="OK, adjust quantity" onConfirm={this.onAdjustQuantity.bind(this)}>
                                    <Message warning icon>
                                        <Icon name="warning" />
                                        <Message.Content>
                                            <Message.Header>Warning</Message.Header>
                                            Quantity changes are tracked and will be recorded in the history of this inventory item.
                                        </Message.Content>
                                        <Form>
                                            <Form.Input
                                                type="number"
                                                name="newQuantity"
                                                label="New Quantity"
                                                placeholder="Enter new quantity"
                                                defaultValue={this.props.inventoryItem.quantity}
                                                required
                                                min={0}
                                                step={1}
                                                onChange={this.onChange.bind(this)}
                                            />
                                        </Form>
                                    </Message>
                                </ApiButtonModal>
                            </Table.Cell>
                        </Table.Row>}

                        <Table.Row>
                            <Table.HeaderCell width={3}>ID</Table.HeaderCell>
                            <Table.Cell><strong>{this.props.inventoryItem.id}</strong>&nbsp;<Button size="tiny" onClick={() => { navigator.clipboard.writeText(this.props.inventoryItem.id) }}>Copy</Button></Table.Cell>
                        </Table.Row>

                        <Table.Row>
                            <Table.HeaderCell width={3}>Creator</Table.HeaderCell>
                            <Table.Cell><a href={`/account/${this.props.inventoryItem.creatorBigscreenAccountId}`}>View account</a></Table.Cell>
                        </Table.Row>

                        <Table.Row>
                            <Table.HeaderCell width={3}>Created</Table.HeaderCell>
                            <Table.Cell>{createdAt} ({fromNow})</Table.Cell>
                        </Table.Row>

                        <Table.Row>
                            <Table.HeaderCell width={3}>State</Table.HeaderCell>
                            <Table.Cell><Label color={stateLabelColor} horizontal>{inventoryItemState}</Label></Table.Cell>
                        </Table.Row>

                        {(this.props.inventoryItem.trackingType !== 'QuantityTracked') && <Table.Row>
                            <Table.HeaderCell width={3}>Location</Table.HeaderCell>
                            <Table.Cell>
                                <InventoryItemPickingHint pickingHint={this.props.inventoryItem.pickingHint} />
                            </Table.Cell>
                        </Table.Row>}

                        {this.props.inventoryItem.jobId && <Table.Row>
                            <Table.HeaderCell width={3}>Job</Table.HeaderCell>
                            <Table.Cell><Button inverted color="blue" size="tiny" href={`/fabricator/job/${this.props.inventoryItem.jobId}`}><Icon name='cog' />Job #{this.props.inventoryItem.jobId}</Button></Table.Cell>
                        </Table.Row>}
                    </Table.Body>
                </Table>
                <Table compact celled padded>
                    <Table.Header>
                        <Table.Row>
                            <Table.HeaderCell width={2}>When</Table.HeaderCell>
                            <Table.HeaderCell width={2}>User</Table.HeaderCell>
                            <Table.HeaderCell fluid>Message</Table.HeaderCell>
                        </Table.Row>
                    </Table.Header>
                    <Table.Body>
                        {history}
                    </Table.Body>
                </Table>
                <Segment color="red">
                    <Header as="h2" color="red">Danger Zone</Header>
                    <Table compact celled definition>
                        <Table.Body>
                            <Table.Row>
                                <Table.HeaderCell width={4}>Permanently Delete</Table.HeaderCell>
                                <Table.Cell>
                                    <ApiButtonModal color="red" size="small" icon="trash alternate outline" text="Permanently delete this inventory item" modalIcon="trash alternate outline" modalButtonText="OK, permanently delete this inventory item" onConfirm={this.onDeleteInventoryItem.bind(this)}>
                                        Are you sure you want to permanently delete this inventory item?
                                        <br />
                                        <Message warning icon>
                                            <Icon name="warning" />
                                            <Message.Content>
                                                <Message.Header>Warning</Message.Header>
                                                This action can not be undone! Deleting an inventory item after it has shipped may cause problems with the database!!!
                                            </Message.Content>
                                        </Message>
                                    </ApiButtonModal>
                                </Table.Cell>
                            </Table.Row>
                        </Table.Body>
                    </Table>
                </Segment>
            </div>
        )
    }
}
