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

import * as ApiUtils from '../CloudApi/ApiUtils.js';
import constants, { DEFAULT_TIMEZONE } from '../CloudApi/Constants.js';
import WaxIdBitField from './WaxIdBitField.jsx';
import ToolPathDownloadButton from './ToolPathDownloadButton.jsx';

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

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

    showRevokeScanRequestModal() {}

    openRevokeScanRequestModal(i, e) {
        this.setState({ revokeScanRequestModalOpen: true});
    }

    closeRevokeScanRequestModal(i, e) {
        this.setState({ revokeScanRequestModalOpen: false});
    }

    async onRevokeScanRequest(e) {
        e.preventDefault();
        this.setState({ loading: true });
        try {
            let res = await superagent.put(`/api/admin/fabricator/scan_request/${scanRequest.id}`).send({
                scanRequestState: this.props.schemas.ScanRequestStates["Revoked"]
            });
            window.location.reload();
        } catch (e) {
            window.alert("Error sending scan request email: " + e.message);
            console.error(e);
        }

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

    onClickScanRequest(scanRequest, e) {
        window.location.href = `/fabricator/scan_request/${scanRequest.id}`;
    }

    renderIpdLabel() {

    }

    renderScanRequestRow(scanRequest) {
        if (scanRequest.scanRequestState === this.props.schemas.ScanRequestStates["Revoked"]) {
            return (
                <ClickableTableRow href={`/fabricator/scan_request/${scanRequest.id}`}>
                    <Table.Cell colSpan='6'>
                        Hiding revoked scan request {scanRequest.id}
                    </Table.Cell>
                </ClickableTableRow>
            );
        }

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

        const scanRequestState = Object.entries(this.props.schemas.ScanRequestStates).find(entry => entry[1] === scanRequest.scanRequestState)[0];
        const stateLabelColor = (scanRequest.scanRequestState === this.props.schemas.ScanRequestStates["VerifiedAndReady"]) ? "green" : "grey";

        let ipdLabel = <Label color="orange">IPD Not Set</Label>;
        if (scanRequest.ipd !== -1) {
            ipdLabel = <Label color="blue">{scanRequest.ipd}mm</Label>
        }

        return (
            <ClickableTableRow key={scanRequest.id} href={`/fabricator/scan_request/${scanRequest.id}`}>
                <Table.HeaderCell><strong>{scanRequest.id}</strong>&nbsp;<Button size="tiny" onClick={() => {navigator.clipboard.writeText(scanRequest.id)}}>Copy</Button></Table.HeaderCell>
                <Table.Cell>{createdAt} ({fromNow})</Table.Cell>
                <Table.Cell><Label color={stateLabelColor} horizontal>{scanRequestState}</Label></Table.Cell>
                <Table.Cell>{ipdLabel}</Table.Cell>
                <Table.Cell>
                {(scanRequest.jobIds && scanRequest.jobIds.length > 0) &&
                    <div>{scanRequest.jobIds.map(jobId => <Button inverted color="blue" size="tiny" href={`/fabricator/job/${jobId}`}><Icon name='cog' />Job #{jobId}</Button>)}</div>
                }
                </Table.Cell>
            </ClickableTableRow>
        )
    }

    render() {
        if (this.props.loading) {
            return (
                <Segment basic loading={this.props.loading} />
            );
        } else {
            return (
                <div>
                    <Header as="strong">Scan Requests</Header>

                    <Table singleLine celled selectable>
                        <Table.Header>
                            <Table.Row>
                                <Table.HeaderCell collapsing width={2}>ID</Table.HeaderCell>
                                <Table.HeaderCell collapsing width={2}>Created At</Table.HeaderCell>
                                <Table.HeaderCell collapsing width={2}>State</Table.HeaderCell>
                                <Table.HeaderCell collapsing width={2}>IPD</Table.HeaderCell>
                                <Table.HeaderCell collapsing width={2}>Jobs</Table.HeaderCell>
                            </Table.Row>
                        </Table.Header>
                        <Table.Body>
                            {this.props.scanRequests.map(scanRequest => this.renderScanRequestRow(scanRequest))}
                        </Table.Body>
                    </Table>

                    
                    <Modal dimmer="inverted" closeOnEscape={true} closeOnDimmerClick={true} closeIcon
                        onClose={this.closeRevokeScanRequestModal.bind(this)}
                        open={this.state.revokeScanRequestModalOpen}>
                        <Header icon='user' content='Revoke this scan request' />
                        <Modal.Content>
                            Are you sure you want to revoke this scan request?
                        </Modal.Content>
                        <Modal.Actions>
                            <Button color='red' loading={this.state.loading} onClick={this.onRevokeScanRequest.bind(this)}>
                                <Icon name='trash alternate outline' />Yes, Revoke This Scan Request
                            </Button>
                        </Modal.Actions>
                    </Modal>
                </div>
            );
        }
    }
}
