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

import MoviesTVWrapper from './MoviesTVWrapper.jsx';

import {
    Container,
    Segment,
    Header,
    Table,
    Label,
    Button,
    Form, Transition, List
} from 'semantic-ui-react'
import { DEFAULT_TIMEZONE } from '../CloudApi/Constants.js';

export default class Coupons extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            entitlementClasses: [],
            coupons: [],
            newCoupons: null,
            quantity: 1
        };
    }

    async componentDidMount() {
        this.setState({ loading: true });
        const res = await superagent.get(`/api/admin/media/coupons`).accept('json');
        this.setState({ coupons: res.body });

        const schemaRes = await superagent.get("/api/admin/media/schemas");
        const entitlementClasses = Object.keys(schemaRes.body.EntitlementClass).map(k => { return { "key": k, "value": k, "text": k } });
        const mediaTypes = Object.keys(schemaRes.body.MediaType).map(k => { return { "key": k, "value": k, "text": k } });
        this.setState({ schemas: schemaRes.body, entitlementClasses, mediaTypes, loading: false });
    }

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

    async onGenerateCoupons() {
        this.setState({ newCoupons: null, loading: true });
        let res = await superagent.post(`/api/admin/media/coupons`).send({
            entitlementClass: this.state.entitlementClass,
            quantity: this.state.quantity
        });
        
        this.setState({ newCoupons: res.body, loading: false });

        res = await superagent.get(`/api/admin/media/coupons`).accept('json');
        this.setState({ coupons: res.body, loading: false });
    }

    renderCoupon(coupon) {
        const timezone = DEFAULT_TIMEZONE;
        const created = (coupon.createdAt && coupon.createdAt._seconds) ? formatInTimeZone(fromUnixTime(coupon.createdAt._seconds), timezone, 'PPPp z') : "Error";
        const activationTimestamp = (coupon.activationTimestamp && coupon.activationTimestamp._seconds) ? formatInTimeZone(fromUnixTime(coupon.activationTimestamp._seconds), timezone, 'PPPp z') : null;
        const expirationTimestamp = (coupon.expirationTimestamp && coupon.expirationTimestamp._seconds) ? formatInTimeZone(fromUnixTime(coupon.expirationTimestamp._seconds), timezone, 'PPPp z') : null;

        return (
            <Table.Row disabled={coupon.entitlementId !== null}>
                <Table.Cell collapsing>{created}</Table.Cell>
                <Table.Cell collapsing>
                    {expirationTimestamp}
                </Table.Cell>
                <Table.Cell collapsing><Label horizontal>{coupon.entitlementClass || coupon.bigMediaId}</Label></Table.Cell>
                <Table.Cell collapsing>{coupon.code}
                    {!coupon.entitlementId && <Button size="tiny" onClick={() => {navigator.clipboard.writeText(coupon.code)}}>Copy</Button>}
                </Table.Cell>
                <Table.Cell>
                    {coupon.entitlementId ? <Label horizontal color="blue">Claimed on {activationTimestamp} ({coupon.entitlementId})</Label> : <Label horizontal basic color="green">Unclaimed</Label>}
                    {activationTimestamp && <Label horizontal>{activationTimestamp}</Label>}
                </Table.Cell>
            </Table.Row>
        )
    }

    render() {
        return (
            <MoviesTVWrapper title="Coupons" loading={this.state.loading}>
                <Header as="h4">Create coupons</Header>

                <Form size='small' loading={this.state.loading} onSubmit={this.onGenerateCoupons.bind(this)}>
                    <Form.Group>
                        <Form.Select
                            required
                            width={3}
                            size="tiny"
                            label='Entitlement Class'
                            name="entitlementClass"
                            value={this.state.entitlementClass}
                            options={this.state.entitlementClasses}
                            onChange={this.onChange.bind(this)}
                        />
                        <Form.Input width={3} required label='Quantity' value={this.state.quantity} name="quantity" onChange={this.onChange.bind(this)} />
                    </Form.Group>

                    <Form.Group>
                        <Form.Button primary content='Create coupons' type='submit' />
                    </Form.Group>
                </Form>
                
                {this.state.newCoupons &&
                    <Segment>
                        <h4>Created coupons:</h4>{this.state.newCoupons.map(coupon => <Label>{coupon.code}</Label>)}
                        <Button icon="clipboard" color="blue" onClick={() => {
                            let couponCodes = this.state.newCoupons.map(coupon => coupon.code).join(", ");
                            navigator.clipboard.writeText(couponCodes);
                        }}>Copy coupon codes to clipboard</Button>
                        <Table celled striped compact>
                            <Table.Header>
                                <Table.Row>
                                    <Table.HeaderCell collapsing>Issued</Table.HeaderCell>
                                    <Table.HeaderCell collapsing>Expiration</Table.HeaderCell>
                                    <Table.HeaderCell collapsing>Type</Table.HeaderCell>
                                    <Table.HeaderCell collapsing>Code</Table.HeaderCell>
                                    <Table.HeaderCell>Status</Table.HeaderCell>
                                </Table.Row>
                            </Table.Header>
                            <Table.Body>
                            {this.state.newCoupons.map(coupon => this.renderCoupon(coupon))}
                            </Table.Body>
                        </Table>
                    </Segment>
                }
                
                <Segment basic>
                    <h4>Full coupon list:</h4>
                    <Table celled striped compact>
                        <Table.Header>
                            <Table.Row>
                                <Table.HeaderCell collapsing>Issued</Table.HeaderCell>
                                <Table.HeaderCell collapsing>Expiration</Table.HeaderCell>
                                <Table.HeaderCell collapsing>Type</Table.HeaderCell>
                                <Table.HeaderCell collapsing>Code</Table.HeaderCell>
                                <Table.HeaderCell>Status</Table.HeaderCell>
                            </Table.Row>
                        </Table.Header>
                        <Table.Body>
                        {this.state.coupons.map(coupon => this.renderCoupon(coupon))}
                        </Table.Body>
                    </Table>
                </Segment>
            </MoviesTVWrapper>
        );
    }
}
