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

import {Button, Header, Label, Table, Image, Modal, Icon} from 'semantic-ui-react';
import { DEFAULT_TIMEZONE } from '../CloudApi/Constants.js';

class EntitlementRow extends React.Component {
    constructor(props) {
        super(props);
    }

    async componentDidMount() {
    }

    render() {
        if (!this.props.entitlement) {
            return <div />;
        }

        const timezone = DEFAULT_TIMEZONE;
        const createdAt = formatInTimeZone(fromUnixTime(this.props.entitlement.createdAt._seconds), timezone, 'PPPpp z');
        const start = (this.props.entitlement.activationTimestamp) ? formatInTimeZone(fromUnixTime(this.props.entitlement.activationTimestamp._seconds), timezone, 'PPPp z') : "N/A";
        const end = (this.props.entitlement.activationTimestamp) ? formatInTimeZone(fromUnixTime(this.props.entitlement.expirationTimestamp._seconds), timezone, 'PPPp z') : "N/A";

        let receipt = (
            <div />
        );

        let productImage = (this.props.entitlement.productSnapshot.marketingData && this.props.entitlement.productSnapshot.marketingData["en-US"] && this.props.entitlement.productSnapshot.marketingData["en-US"].unityPosterTexture) &&
            <Image floated="left" src={this.props.entitlement.productSnapshot.marketingData["en-US"].unityPosterTexture["src"]} size="mini" />;

        let paymentMethod, labelColor, paymentId, sku, amount, currency = null;
        if (this.props.entitlement.receiptSnapshot) {
            const receiptSnapshot = this.props.entitlement.receiptSnapshot;
            const productSnapshot = this.props.entitlement.productSnapshot;
            if (receiptSnapshot.stripePaymentResult) {
                if (receiptSnapshot.stripePaymentResult.zeroPriceSku) {
                    labelColor = "teal";
                    paymentMethod = "FREE $0.00";
                    paymentId = receiptSnapshot.id;
                    sku = `free_${this.props.entitlement.bigMediaId}`;
                    amount = 0;
                    currency = "usd";
                } else {
                    const skuId = receiptSnapshot.stripePaymentResult.items
                        && receiptSnapshot.stripePaymentResult.items.length > 0
                        ? receiptSnapshot.stripePaymentResult.items[0].parent
                        : productSnapshot.id;
                    labelColor = "blue";
                    paymentMethod = "Stripe";
                    paymentId = receiptSnapshot.stripePaymentResult.id;
                    sku = skuId;
                    amount = receiptSnapshot.stripePaymentResult.amount;
                    currency = receiptSnapshot.stripePaymentResult.currency;
                }
            } else if (receiptSnapshot.oculusPurchaseData) {
                labelColor = "black";
                paymentMethod = "Oculus-IAP";
                paymentId = receiptSnapshot.oculusPurchaseData.oculusPurchaseId;
                sku = receiptSnapshot.oculusPurchaseData.id;
                amount = receiptSnapshot.oculusPurchaseData.price;
                currency = receiptSnapshot.oculusPurchaseData.currency;
            } else if (receiptSnapshot.couponId) {
                labelColor = "orange";
                paymentMethod = "Coupon";
                paymentId = receiptSnapshot.couponId;
                sku = receiptSnapshot.id;
                amount = receiptSnapshot.price;
                currency = receiptSnapshot.currency;
            }
        }

        return (
            <Table.Row>
                <Table.Cell>
                {productImage}
                    <a style={{ fontWeight: "lighter" }} href={`/cinema/product/${this.props.entitlement.productSnapshot.id}`}>{this.props.entitlement.productSnapshot.title}</a>
                </Table.Cell>
                <Table.Cell>
                    {(this.props.entitlement.receiptSnapshot) &&
                        <div>
                            <Label color={labelColor}>{paymentMethod}</Label>
                            {amount} {currency}<br />
                            <small>PurchaseID: {paymentId}</small>
                        </div>
                    }
                    
                </Table.Cell>
                <Table.Cell>{createdAt}</Table.Cell>
                {this.props.showAccount && <Table.Cell>
                    <Header as='h3' image>
                        <Image src='/images/avatar_b.jpg' rounded size='mini' />
                        <Header.Content>
                            <Header.Subheader>Purchaser: <a href={`/account/${this.props.entitlement.bigscreenAccount.id}`}>{this.props.entitlement.bigscreenAccount.username}</a></Header.Subheader>
                        </Header.Content>
                    </Header>
                </Table.Cell>}
                
                <Table.Cell>
                    {this.props.entitlement.entitlementClass}
                    <br /><small>ID: {this.props.entitlement.id}</small>
                </Table.Cell>
                <Table.Cell>{this.props.entitlement.status}</Table.Cell>
                <Table.Cell> {start} - {end}</Table.Cell>
                <Table.Cell><Button onClick={this.props.onRevoke}>Revoke!</Button></Table.Cell>
            </Table.Row>
        )
    }
}

export default class EntitlementsList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            showRevokeModal: false,
            selectedEntitlement: null,
        };
    }

    onTryRevoke(selectedEntitlement, e) {
        this.setState({showRevokeModal: true, selectedEntitlement });
    }

    closeRevokeModal(e) {
        this.setState({showRevokeModal: false});
    }

    async onRevokeConfirmed(e) {
        e.preventDefault();
        if (this.state.selectedEntitlement) {
            try {
                const result = await superagent.put(`/api/admin/media/entitlement/${this.state.selectedEntitlement.id}`).accept('json')
                    .send({
                        status: "REVOKED"
                    });
                console.log(result.body);
                window.location.reload(true);
            } catch (e) {
                console.log(e);
            }
        }
        this.setState({showRevokeModal: false, selectedEntitlement: undefined});
    }

    render() {
        if (this.props.entitlements) {
            return (
                <div>
                    {this.state.selectedEntitlement && <Modal dimmer="inverted" closeOnEscape={true} closeOnDimmerClick={true} closeIcon
                        onClose={this.closeRevokeModal.bind(this)}
                        open={this.state.showRevokeModal}>
                        <Header icon='user' content='Revoke Entitlement' />
                        <Modal.Content><p>Revoke this entitlement?<br /><br />Title: {this.state.selectedEntitlement.productSnapshot.title}<br />ID: {this.state.selectedEntitlement.id}</p></Modal.Content>
                        <Modal.Actions>
                            <Button color='red' fluid onClick={this.onRevokeConfirmed.bind(this)}>
                                <Icon name='checkmark' />Yes, revoke this entitlement
                            </Button>
                        </Modal.Actions>
                    </Modal>}

                    <Table compact celled definition>
                        <Table.Header>
                            <Table.Row>
                                <Table.HeaderCell width={1}>Title</Table.HeaderCell>
                                <Table.HeaderCell width={1}>Purchase Info</Table.HeaderCell>
                                <Table.HeaderCell width={1}>Date</Table.HeaderCell>
                                {this.props.showAccount && <Table.HeaderCell width={1}>Purchaser</Table.HeaderCell>}
                                <Table.HeaderCell width={1}>Entitlement Class</Table.HeaderCell>
                                <Table.HeaderCell width={1}>Status</Table.HeaderCell>
                                <Table.HeaderCell width={1}>Availability</Table.HeaderCell>
                                <Table.HeaderCell width={1}>Tools</Table.HeaderCell>
                            </Table.Row>
                        </Table.Header>
                        
                        <Table.Body>
                        {this.props.entitlements.map(entitlement => {
                            return (
                                <EntitlementRow showAccount={this.props.showAccount} entitlement={entitlement} onRevoke={this.onTryRevoke.bind(this, entitlement)} />
                            );
                        })}
                        </Table.Body>
                    </Table>
                </div>
            );
        } else {
            return <div />
        }
    }
}
