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 WaxIdBitField from './WaxIdBitField.jsx';
import * as ApiUtils from '../CloudApi/ApiUtils.js';
import ToolPathDownloadButton from './ToolPathDownloadButton.jsx';

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

export default class Job extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            currentMediaProduct: null,
            initializingJob: false,
            isShowingDestroyJobModal: false,
            isShowingResetJobModal: false,
            reasonToDestroy: "",
            reasonToReset: ""
        };
    }

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

        // inventory items
        const res = await superagent.get(`/api/admin/inventory/items?jobId=${this.props.job.id}`).accept('json');
        console.log(res.body);
        this.setState({inventoryItems: res.body.items});
        
    }

    onChange(e, { name, value }) {
        this.setState({ [name]: value })
        console.log(name, value);
    }
    /*
    onRadioChange(e { value }) {
        this.setState({ "": value })
    }*/

    showDestroyJobModal(jobIndex, e) {
        this.setState({ isShowingDestroyJobModal: true });
    }

    async onConfirmDestroyJob(e) {
        e.preventDefault();

        this.setState({ loading: true });

        try {
            const payload = {
                action: this.props.schemas.JobActions["DestroyJob"],
                metaData: {
                    reason: this.state.reasonToDestroy
                }
            };

            const res = await superagent.put(`/api/admin/fabricator/job/${this.props.job.id}`).send(payload);
            this.setState({ isShowingDestroyJobModal: false });
        } catch (e) {
            console.error(e);
            this.setState({ error: e.request.body });
        }

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

    closeDestroyJobModal(e) {
        this.setState({ isShowingDestroyJobModal: false });
    }

    showResetJobModal(jobIndex, e) {
        this.setState({ isShowingResetJobModal: true });
    }

    async onConfirmResetJob(e) {
        e.preventDefault();

        this.setState({ loading: true });

        console.log(this.state.selectedResetAction);

        try {
            const payload = {
                action: this.state.selectedResetAction,
                metaData: {
                    reason: this.state.reasonToReset
                }
            };
            const res = await superagent.put(`/api/admin/fabricator/job/${this.props.job.id}`).send(payload);
            this.setState({ isShowingResetJobModal: false });
        } catch (e) {
            console.error(JSON.stringify(e, null, 2));
            this.setState({ error: e.response.error.status });

            if (e.response.body.message) {
                this.setState({ errorMessage: e.response.body.message });
            }
        }
        this.setState({ loading: false });
    }

    closeResetJobModal(e) {
        this.setState({ isShowingResetJobModal: false, error: null });
    }

    async onRevertJob() {
        try {
            this.setState({ loading: true });

            let res = await superagent.get(`/api/admin/fabricator/job/${this.props.job.id}/debug_revert_history`).send();
            window.location.href = `/fabricator/job/${this.props.job.id}`;
        } catch (e) {
            console.error(e);
        }
        this.setState({ loading: false });
    }

    render() {
        if (!this.props.job || !this.props.schemas) {
            return (
                <div />
            )
        }

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

        const jobState = Object.entries(this.props.schemas.JobStates).find(entry => entry[1] === this.props.job.jobState)[0];
        const machineIdHistory = _.last(_.filter(this.props.job.history, item => item.metaData && item.metaData.machineId && item.metaData.machineId.startsWith("cb")));

        const MAX_REASON_LENGTH = 10;

        return (
            <div>
                <Modal dimmer="inverted" closeOnEscape={true} closeOnDimmerClick={true} closeIcon
                    onClose={this.closeResetJobModal.bind(this)}
                    open={this.state.isShowingResetJobModal}>
                    <Header icon='cog' content='Reset this Job' />
                    <Modal.Content>
                        <Message warning icon>
                            <Icon name="warning" />
                            <Message.Content>
                                <Message.Header>Warning</Message.Header>
                                This action can not be undone! Resetting a job will change the customer's order to be delayed.
                            </Message.Content>
                        </Message>

                        {this.state.error &&
                            <Message negative icon>
                                <Icon name="warning" />
                                <Message.Content>
                                    <Message.Header>Error</Message.Header>
                                    {this.state.error} - status not allowed. Choose a different action.
                                    {this.state.errorMessage && <p>{`Reason: ${this.state.errorMessage}.`}</p>}
                                </Message.Content>
                            </Message>
                        }

                        <p>Select the status to reset this job to:</p>
                        <Form>
                            <Form.Field>
                                <Radio toggle
                                    label='Awaiting Scan Verification -- completely rebuild the job from the customer scan.'
                                    name='selectedResetAction'
                                    value={this.props.schemas.JobActions["ResetToAwaitingScanVerification"]}
                                    checked={this.state.selectedResetAction === this.props.schemas.JobActions["ResetToAwaitingScanVerification"]}
                                    onChange={this.onChange.bind(this)}
                                />
                            </Form.Field>
                            <Form.Field>
                                <Radio toggle
                                    label='Awaiting Toolpath -- regenerate the tool path file in Fusion360.'
                                    name='selectedResetAction'
                                    value={this.props.schemas.JobActions["ResetToAwaitingToolpath"]}
                                    checked={this.state.selectedResetAction === this.props.schemas.JobActions["ResetToAwaitingToolpath"]}
                                    onChange={this.onChange.bind(this)}
                                />
                            </Form.Field>
                            <Form.Field>
                                <Radio toggle
                                    label='Awaiting Manufacturing -- to run the wax mold through the CNC.'
                                    name='selectedResetAction'
                                    value={this.props.schemas.JobActions["ResetToAwaitingManufacture"]}
                                    checked={this.state.selectedResetAction === this.props.schemas.JobActions["ResetToAwaitingManufacture"]}
                                    onChange={this.onChange.bind(this)}
                                />
                            </Form.Field>
                            <Form.Field>
                                <Radio toggle
                                    label='Awaiting NFC -- to reassign the NFC tag.'
                                    name='selectedResetAction'
                                    value={this.props.schemas.JobActions["ResetToAwaitingNFC"]}
                                    checked={this.state.selectedResetAction === this.props.schemas.JobActions["ResetToAwaitingNFC"]}
                                    onChange={this.onChange.bind(this)}
                                />
                            </Form.Field>
                            <p>Enter a reason to reset this job:</p>

                            <Form.Group inline widths="equal">
                                <Form.Input width={10} size="medium" name="reasonToReset" value={this.state.reasonToReset} onChange={this.onChange.bind(this)} />
                            </Form.Group>
                        </Form>
                    </Modal.Content>
                    <Modal.Actions>
                        <Button color='red' loading={this.state.loading} disabled={this.state.reasonToReset === null || this.state.reasonToReset.length < MAX_REASON_LENGTH} onClick={this.onConfirmResetJob.bind(this)}>
                            <Icon name='checkmark' />Yes, reset this job
                        </Button>
                    </Modal.Actions>
                </Modal>

                <Modal dimmer="inverted" closeOnEscape={true} closeOnDimmerClick={true} closeIcon
                    onClose={this.closeDestroyJobModal.bind(this)}
                    open={this.state.isShowingDestroyJobModal}>
                    <Header icon='delete' content='Destroy' />
                    <Modal.Content>
                        <Message warning icon>
                            <Icon name="warning" />
                            <Message.Content>
                                <Message.Header>Warning</Message.Header>
                                This action can not be undone! This may cause the customer's order to be delayed while a new job is created!
                            </Message.Content>
                        </Message>
                        <p>Enter a reason to destroy this job:</p>
                        <Form.Input fluid size="medium" name="reasonToDestroy" value={this.state.reasonToDestroy} onChange={this.onChange.bind(this)} />
                    </Modal.Content>
                    <Modal.Actions>
                        <Button color='red' loading={this.state.loading} disabled={this.state.reasonToDestroy === null || this.state.reasonToDestroy.length < MAX_REASON_LENGTH} onClick={this.onConfirmDestroyJob.bind(this)}>
                            <Icon name='checkmark' />Yes, destroy this job
                        </Button>
                    </Modal.Actions>
                </Modal>

                {this.props.job.jobState === this.props.schemas.JobStates["Destroyed"] && <Message icon color='red'>
                    <Icon name="trash alternate outline" />
                    <Message.Content>
                        <Message.Header>This job is destroyed!</Message.Header>
                        The job can not be recreated.  What is going on? How could this happen?
                    </Message.Content>
                </Message>}

                {this.props.job.looperStatus === "Stalled" && <Message icon>
                    <Icon name="warning" />
                    <Message.Content>
                        <Message.Header>This job is stalled</Message.Header>
                        The job has been stuck in the same state for more than two weeks. What's going on????
                    </Message.Content>
                </Message>}

                <Table compact singleLine loading={this.state.loading}>
                    {this.props.job.jobState !== this.props.schemas.JobStates["Destroyed"] &&
                        <Table.Header fullWidth>
                            <Table.Row>
                                <Table.HeaderCell>
                                    <Button color='Orange' onClick={this.showResetJobModal.bind(this)}><Icon name='cog' />Reset this job</Button>
                                </Table.HeaderCell>
                                <Table.HeaderCell colSpan='1'>
                                    <Button floated='right' color='red' onClick={this.showDestroyJobModal.bind(this)}><Icon name='trash' />Destroy this job</Button>
                                </Table.HeaderCell>
                            </Table.Row>
                        </Table.Header>}
                    <Table.Body>

                        <Table.Row>
                            <Table.HeaderCell width={3}>ID</Table.HeaderCell>
                            <Table.Cell><strong>{this.props.job.id}</strong>&nbsp;<Button size="tiny" onClick={() => { navigator.clipboard.writeText(this.props.job.id) }}>Copy</Button></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}>Name</Table.HeaderCell>
                            <Table.Cell><strong>{_.isEmpty(this.props.job.name) ? "(none)" : this.props.job.name}</strong></Table.Cell>
                        </Table.Row>

                        <Table.Row>
                            <Table.HeaderCell width={3}>Job Type</Table.HeaderCell>
                            <Table.Cell>{this.props.job.jobType}</Table.Cell>
                        </Table.Row>

                        <Table.Row>
                            <Table.HeaderCell width={3}>Job State</Table.HeaderCell>
                            <Table.Cell><Label horizontal>{jobState}</Label></Table.Cell>
                        </Table.Row>

                        <Table.Row>
                            <Table.HeaderCell width={3}>Priority</Table.HeaderCell>
                            <Table.Cell>{this.props.job.priority}</Table.Cell>
                        </Table.Row>

                        <Table.Row>
                            <Table.HeaderCell width={3}>BigOrder</Table.HeaderCell>
                            <Table.Cell>
                                {this.props.job.bigOrderId ?
                                    <Button inverted color="green" size="tiny" href={`/shop/order/${this.props.job.bigOrderId}`}><Icon name='shopping bag' />View big order...</Button>
                                    : <Message color="orange">No BigOrder Id</Message>
                                }
                            </Table.Cell>
                        </Table.Row>

                        {/* <Table.Row>
                            <Table.HeaderCell width={3}>Bin Location</Table.HeaderCell>
                            <Table.Cell><strong>{this.props.job.binLocation}</strong></Table.Cell>
                        </Table.Row> */}

                        <Table.Row>
                            <Table.HeaderCell width={3}>Bin Location</Table.HeaderCell>
                            <Table.Cell><strong>{this.props.job.binLocation}</strong></Table.Cell>
                        </Table.Row>

                        <Table.Row>
                            <Table.HeaderCell width={3}>Shopify Order Id</Table.HeaderCell>
                            <Table.Cell>{this.props.job.shopifyOrderId}</Table.Cell>
                        </Table.Row>

                        <Table.Row>
                            <Table.HeaderCell width={3}>NFC Tag Id</Table.HeaderCell>
                            <Table.Cell>
                                {this.props.job.nfcTagId ? <Label color="green">{this.props.job.nfcTagId}</Label> : <Label color="orange">None</Label>}
                            </Table.Cell>
                        </Table.Row>

                        {machineIdHistory && <Table.Row>
                            <Table.HeaderCell width={3}>Last CB Machine Id</Table.HeaderCell>
                            <Table.Cell>
                                <Label color="teal">{machineIdHistory.metaData.machineId}</Label>
                            </Table.Cell>
                        </Table.Row>}

                        {this.props.job.toolPathBitFieldSnapshot &&
                            <Table.Row>
                                <Table.HeaderCell width={3}>ToolPath File</Table.HeaderCell>
                                <Table.Cell>
                                    <ToolPathDownloadButton job={this.props.job} />
                                </Table.Cell>
                            </Table.Row>}

                        {this.props.job.toolPathBitFieldSnapshot &&
                            <Table.Row>
                                <Table.HeaderCell width={3}>Tool path bit field</Table.HeaderCell>
                                <Table.Cell>
                                    <WaxIdBitField job={this.props.job} />
                                </Table.Cell>
                            </Table.Row>}

                        {this.state.inventoryItems &&
                            <Table.Row>
                                <Table.HeaderCell width={3}>Inventory items</Table.HeaderCell>
                                <Table.Cell>
                                    {this.state.inventoryItems.map(item => <Button color="blue" inverted href={`/inventory/item/${item.id}`}>{item.id} ({item.status})</Button>)}
                                </Table.Cell>
                            </Table.Row>}

                        <Table.Row>
                            <Table.HeaderCell width={3}>Version</Table.HeaderCell>
                            <Table.Cell>{this.props.job.version}</Table.Cell>
                        </Table.Row>

                    </Table.Body>
                </Table>
                <Table compact celled padded>
                    <Table.Header>
                        <Table.Row>
                            <Table.HeaderCell width={1}>Tools</Table.HeaderCell>
                            <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>
                        {this.props.job.history && this.props.job.history.map((historyItem, historyItemIndex) => {
                            let createdAtDateTime = fromUnixTime(historyItem.createdAt / 1000);
                            const createdAt = formatInTimeZone(createdAtDateTime, DEFAULT_TIMEZONE, 'PPPp z');
                            return (<Table.Row>
                                <Table.Cell width={1}>
                                    {(historyItemIndex == this.props.job.history.length - 1) && <Button size="tiny" loading={this.state.loading} onClick={this.onRevertJob.bind(this)}>Revert</Button>}
                                </Table.Cell>
                                <Table.Cell width={2}>
                                    {createdAt}
                                </Table.Cell>
                                <Table.Cell width={2}>
                                    {historyItem.bigscreenAccountId}
                                </Table.Cell>
                                <Table.Cell>
                                    {historyItem.message}
                                    {(historyItem.metaData && historyItem.metaData.reason) && <div><strong>Reason:</strong> {historyItem.metaData.reason}</div>}
                                    {(historyItem.metaData && historyItem.metaData.machineId) && <div><strong>Machine Id:</strong><Label color="teal">{historyItem.metaData.machineId}</Label></div>}
                                </Table.Cell>
                            </Table.Row>);
                        })}
                    </Table.Body>
                </Table>
            </div>
        );
    }
}
