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 ReactPlayer from 'react-player'

import {formatPrice}  from '../Util/formatters';
import constants, { DEFAULT_TIMEZONE } from '../CloudApi/Constants.js';
import MoviesTVWrapper from './MoviesTVWrapper.jsx';
import MediaItemInfoPanel from './MediaItemInfoPanel.jsx';

import {
    Container,
    Segment,
    Grid,
    Header,
    Image,
    Icon,
    Button,
    Table,
    Form,
    Label,
    Message,
    Menu,
    Tab,
    Dropdown,
    Radio,
    Divider
} from 'semantic-ui-react'

export default class MediaProductEditor extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            product: {
                title: "",
                description: "",
                mediaItems: [],
                mediaItemIds: [],
                roomSettings: {},
                entitlementClass: "",
                featuredMediaItemId: "",
                is3D: false,
                locationCodes: null,
                pricingProfileFilter: 0
            },
            locationSKUs: {},
            allMediaItems: [],
            mediaItemsOptions: [],
            mediaProductTrailers: [],
            trailerOptions: [],
            messages: null,
            entitlementClasses: [],
            loadingShowings: false,
            showings: [],
            loadingMediaSessionEvents: false,
            mediaSessionEvents: [],
        };
    }

    async componentDidMount() {
        this.setState({ loading: true });
        const responses = await Promise.all([
            this.reloadProduct(),
            superagent.get(`/api/admin/media/items`).accept('json'),
            superagent.get(`/api/admin/media/products?entitlementClass=FREE_FOR_ALL`).accept('json'),
            superagent.get("/api/admin/media/schemas")
        ]);

        const allMediaItems = responses[1].body;
        const mediaItemsOptions = allMediaItems.map(nv => { return { "key": nv.id, "value": nv.id, "text": `${nv.title} (${nv.cdn})` } });
        this.setState({ allMediaItems, mediaItemsOptions });

        const mediaProductTrailers = responses[2].body;
        const trailerOptions = mediaProductTrailers.map(mediaProduct => {
            return {
                "key": mediaProduct.bigMediaId,
                "value": mediaProduct.bigMediaId,
                "text": `${mediaProduct.title}`,
                "image": { src: mediaProduct.marketingData["en-US"].unityPosterTexture && mediaProduct.marketingData["en-US"].unityPosterTexture["src"] }
            }
        });
        this.setState({ mediaProductTrailers, trailerOptions });

        const schemas = responses[3].body;
        const entitlementClasses = Object.keys(schemas.EntitlementClass).map(k => { return { "key": k, "value": k, "text": k } });
        const mediaTypes = Object.keys(schemas.MediaType).map(k => { return { "key": k, "value": k, "text": k } });
        this.setState({ schemas, entitlementClasses, mediaTypes, loading: false });
    }

    async reloadProduct() {
        if (this.props.match.params.productId) {
            this.setState({ loading: true, messages: null });
            const res = await superagent.get(`/api/admin/media/product/${this.props.match.params.productId}`).accept('json');
            console.log(res.body);
            this.setState({ product: res.body });

            await Promise.all([
                this.generateShowings(),
                this.generateMediaSessionEvents()
            ]);
        }
    }

    async onSaveProduct() {
        this.setState({ loading: true });
        try {
            if (this.state.product.id) {
                const res = await superagent.put(`/api/admin/media/product`).send(this.state.product);
                console.log(res);
                //this.setState({ loading: false });
            } else {
                const res = await superagent.post(`/api/admin/media/product`).send(this.state.product);
                this.props.history.push({pathname: `/cinema/product/${res.body.id}`});
                await this.reloadProduct();
            }
            this.setState({ messages: null, loading: false })
        } catch (e) {
            console.log(e.response.body);
            this.setState({ messages: e.response.body, loading: false });
        }
    }

    async onActivate(e) {
        e.preventDefault();
        const product = this.state.product;
        const ACTIVATED = "ACTIVATED";
        product.status = this.state.schemas.ProductStatus[ACTIVATED];
        await this.onSaveProduct();
        await this.reloadProduct();
        this.setState({ loading: false });
    }

    async generateShowings() {
        this.setState({ loadingShowings: true });
        const res = await superagent.get(`/api/admin/media/showings/${this.state.product.synchronizationInterval}`).accept('json');
        this.setState({ loadingShowings: false, showings: res.body });
    }

    async generateMediaSessionEvents() {
        this.setState({ loadingMediaSessionEvents: true });
        const res = await superagent.get(`/api/admin/media/events/${this.state.product.id}`).accept('json');
        this.setState({ loadingMediaSessionEvents: false, mediaSessionEvents: res.body });
    }

    async onChange(e, { name, value }) {
        const product = this.state.product;
        product[name] = value;
        this.setState({ product });

        if (name === "synchronizationInterval") {
            await this.generateShowings();
        }

        if (name === "featuredMediaItemId") {
            await this.generateMediaSessionEvents();
        }
    }

    onChangeCurrentChannelRoomSettings(e, { name, value }) {
        if (this.state.product) {
            const product = this.state.product;
            if (!product.roomSettings) {
                product.roomSettings = {};
            }
            product.roomSettings[name] = value;
            console.log(product);
            this.setState({ product });
        }
    }

    onAddMediaItem(e) {
        e.preventDefault();
        let product = this.state.product;
        product.mediaItems.push({
            id: ""
        });
        this.setState({ product });
    }

    render() {
        if (!this.state.product) {
            return (<div />);
        }

        const existingProductInfo = (this.state.product.id) && (
            <Segment>
                <Header as="h3">Product Info</Header>
                <p><strong>ID: </strong> {this.state.product.id}</p>
                <p><strong>BigMediaId: </strong> {this.state.product.bigMediaId}</p>
                <p><strong>Created At: </strong> {(this.state.product.createdAt && this.state.product.createdAt._seconds) ? formatInTimeZone(fromUnixTime(this.state.product.createdAt._seconds), DEFAULT_TIMEZONE, 'PPPp z') : "Error"}</p>
                <p><strong>Status: </strong> {this.state.product.status}</p>
                <p><strong>Duration: </strong> {this.state.product.duration ? (this.state.product.duration / 1000.0) : 0} seconds</p>
            </Segment>
        );

        // Error messages.
        let messages = null;
        if (this.state.messages) {
            if (_.isArray(this.state.messages)) {
                messages = (
                    <Message negative>
                        <Message.Header>Errors:</Message.Header>
                        {this.state.messages.map(message => (
                            <p>{message.msg}</p>
                        ))}
                    </Message>
                );
            } else {
                messages = (
                    <Message negative>
                        {this.state.messages}
                    </Message>
                );
            }
        }

        const basicProductInfo = (
            <div>
                <Message>
                    <Message.Header>NOTE: This title and description is for internal use only!</Message.Header>
                    <p>See the <strong>marketing</strong> tab for customer facing information.</p>
                </Message>

                <Form.Group>
                    <Form.Input autoComplete="off" width={3} required label='Dashboard Title' value={this.state.product.title} name="title" onChange={this.onChange.bind(this)} />
                </Form.Group>

                <Form.Group widths="equal">
                    <Form.TextArea autoComplete="off" required label='Dashboard Description' value={this.state.product.description} name="description" onChange={this.onChange.bind(this)} />
                </Form.Group>

                <Form.Group>
                    <Form.Select readOnly={this.state.product.id !== null}
                        required
                        width={3}
                        size="tiny"
                        label='Entitlement Class'
                        name="entitlementClass"
                        value={this.state.product.entitlementClass}
                        options={this.state.entitlementClasses}
                        onChange={this.onChange.bind(this)}
                    />
                </Form.Group>

                {(this.state.product.url) &&
                    <Form.Group>
                        <Form.Input width={3} label='URL Code' value={this.state.product.url} name="url" onChange={this.onChange.bind(this)} />
                    </Form.Group>}
            </div>
        );

        const mediaItems = (
            <div>
                <Header as="h2">Media Items Playlist</Header>

                <Table celled striped>
                    {(this.state.product.mediaItems.length > 0) && (
                        <Table.Header>
                            <Table.Row>
                                <Table.HeaderCell>Item</Table.HeaderCell>
                                <Table.HeaderCell>Edit</Table.HeaderCell>
                            </Table.Row>
                        </Table.Header>
                    )}
                    <Table.Body>
                        {this.state.product.mediaItems.map((mediaItem, mediaItemIndex) => {
                            let onMediaItemChanged = function (e, { name, value }) {
                                e.preventDefault();
                                let product = this.state.product;
                                product.mediaItemIds[mediaItemIndex] = value;
                                product.mediaItems[mediaItemIndex] = _.find(this.state.allMediaItems, { id: value });
                                this.setState({ product });
                            }
                            let onRemoveMediaItem = function (e) {
                                e.preventDefault();
                                let product = this.state.product;
                                product.mediaItemIds.splice(mediaItemIndex, 1);
                                product.mediaItems.splice(mediaItemIndex, 1);
                                this.setState({ product });
                            }

                            return (
                                <Table.Row>
                                    <Table.Cell verticalAlign="top" collapsing width={1}>#{mediaItemIndex + 1}</Table.Cell>
                                    <Table.Cell width={10} verticalAlign="top">
                                        <Dropdown search selection
                                            placeholder="Type a media item name name or choose an option..."
                                            icon='search'
                                            fluid
                                            loading={this.state.mediaItemsOptions === null}
                                            size="small"
                                            value={mediaItem.id}
                                            name="mediaItemId"
                                            options={this.state.mediaItemsOptions}
                                            onChange={onMediaItemChanged.bind(this)} />
                                        {mediaItem.cdn && <MediaItemInfoPanel mediaItem={mediaItem} />}
                                    </Table.Cell>
                                    <Table.Cell collapsing>
                                        <Button onClick={onRemoveMediaItem.bind(this)}><Icon name='delete' />Remove</Button>
                                    </Table.Cell>
                                </Table.Row>
                            )
                        })}
                    </Table.Body>
                    <Table.Footer fullWidth>
                        <Table.Row>
                            <Table.Cell colSpan='5'><Button onClick={this.onAddMediaItem.bind(this)}>Add Media Item</Button></Table.Cell>
                        </Table.Row>
                    </Table.Footer>
                </Table>
            </div>
        )

        const roomSettings = (
            <div>
                <Header as="h2">Room Settings</Header>

                <Form.Group widths="equal">
                    <Form.Select required label="Environment" size="small" name="environment"
                        value={this.state.product.roomSettings.environment}
                        options={constants.RoomEnvironments}
                        onChange={this.onChangeCurrentChannelRoomSettings.bind(this)} />

                    <Form.Select required label="Size" size="small" name="size"
                        value={this.state.product.roomSettings.size}
                        options={constants.RoomSizes}
                        onChange={this.onChangeCurrentChannelRoomSettings.bind(this)} />
                </Form.Group>
            </div>
        );

        let featuredMediaItemOptions = [
            { "key": "empty", "value": "", "text": "No default selected" }
        ];

        featuredMediaItemOptions = featuredMediaItemOptions.concat(this.state.product.mediaItems.map((mediaItem, mediaItemIndex) => {
            return { "key": mediaItem.id, "value": mediaItem.id, "text": mediaItem.title }
        }));

        const movieNightsInfo = (
            <div>
                <Header as="h2">Movie Nights Info</Header>

                <Message>
                    <Message.Header>Showings Interval - show the movie every X minutes</Message.Header>
                    <p>Use this value to generate "showings" for the movie. A showing is a social movie watching session, where the movie is synchronized for everyone in the session.</p>
                </Message>

                <Grid>
                    <Grid.Column width={4}>
                        <Form.Field label="Showings Interval (In Minutes)">
                        </Form.Field>
                        {constants.SynchronizationIntervals.map(synchronizationInterval => {
                            return (
                                <Form.Field key={synchronizationInterval.value}>
                                    <Radio
                                        value={synchronizationInterval.value}
                                        label={synchronizationInterval.text}
                                        name="synchronizationInterval"
                                        checked={this.state.product.synchronizationInterval === synchronizationInterval.value}
                                        onChange={this.onChange.bind(this)}
                                    />
                                </Form.Field>);
                        })}
                    </Grid.Column>
                    <Grid.Column width={6} loading={this.state.loadingShowings}>
                        <p><strong>Generated Showings (sample)</strong></p>
                        {this.state.showings.map(showing => {
                            return (
                                <Label color="blue" basic>{formatInTimeZone(fromUnixTime(showing), DEFAULT_TIMEZONE, 'PPPp z')}</Label>
                            )
                        })}
                    </Grid.Column>
                </Grid>

                <Header as="h2">Events</Header>

                <Message>
                    <Message.Header>Experimental!</Message.Header>
                    <Message.Content>
                        <p>Starting media item - the media item that starts on time.</p>
                        <p>Featured media item - the main media item that people paid for.</p>
                    </Message.Content>
                </Message>

                <Grid>
                    <Grid.Column width={4}>
                        <Form.Field label="Starting Media Item">
                        </Form.Field>
                        {featuredMediaItemOptions.map(mediaItemOption => {
                            return (
                                <Form.Field key={mediaItemOption.value}>
                                    <Radio
                                        value={mediaItemOption.value}
                                        label={mediaItemOption.text}
                                        name="startingMediaItemId"
                                        checked={this.state.product.startingMediaItemId === mediaItemOption.value}
                                        onChange={this.onChange.bind(this)}
                                    />
                                </Form.Field>);
                        })}
                    </Grid.Column>

                    <Grid.Column width={4}>
                        <Form.Field label="Featured Media Item">
                        </Form.Field>
                        {featuredMediaItemOptions.map(mediaItemOption => {
                            return (
                                <Form.Field key={mediaItemOption.value}>
                                    <Radio
                                        value={mediaItemOption.value}
                                        label={mediaItemOption.text}
                                        name="featuredMediaItemId"
                                        checked={this.state.product.featuredMediaItemId === mediaItemOption.value}
                                        onChange={this.onChange.bind(this)}
                                    />
                                </Form.Field>);
                        })}
                    </Grid.Column>

                    <Grid.Column width={8} loading={this.state.loadingMediaSessionEvents}>
                        <p><strong>Generated Events</strong></p>
                        {this.state.mediaSessionEvents.map(mediaSessionEvent => {
                            return (
                                <div>
                                <Label color="black" basic>{mediaSessionEvent.eventType} (Timestamp: {mediaSessionEvent.timestampOffset / 1000.0} seconds)</Label><br />
                                </div>
                            )
                        })}
                    </Grid.Column>
                </Grid>
            </div>
        );

        let marketingInfo = <div />;

        if (this.state.product.marketingData) {
            const locale = "en-US";
            const selectedMarketingData = this.state.product.marketingData[locale];

            const onChangeMarketingData = (e, { name, value }) => {
                e.preventDefault();
                if (this.state.product) {
                    const product = this.state.product;
                    product.marketingData[locale][name] = value;
                    this.setState({ product });
                }
            }

            const onChangeMarketingDataArray = (e, { name, value }) => {
                e.preventDefault();
                if (this.state.product) {
                    const arrayValue = _.split(value, ", ");
                    const product = this.state.product;
                    product.marketingData[locale][name] = arrayValue;
                    this.setState({ product });
                }
            }

            const onChangeImage = (e, { name, value }) => {
                e.preventDefault();
                if (this.state.product) {
                    const product = this.state.product;
                    product.marketingData[locale][name].src = value;
                    this.setState({ product });
                }
            }

            const on3DChanged = function(e) {
                e.preventDefault();
                if (this.state.product) {
                    const product = this.state.product;
                    product.is3D = !product.is3D;
                    this.setState({ product });
                }
            }

            marketingInfo = (
                <div>
                    <Header as="h2">Marketing Info</Header>

                    <Header as="h3">General Marketing Info</Header>

                    <Message>
                        <Message.Header>Is the customer buying 3D content?</Message.Header>
                        <p>This should only be checked if the "main feature" is 3D. If the main feature is 2D, then set this to false.</p>
                    </Message>

                    <Form.Group widths="equal">
                        <Form.Checkbox label="Is 3D?" checked={this.state.product.is3D} name="is3D" onChange={on3DChanged.bind(this)} />
                    </Form.Group>

                    <Divider />

                    <Header as="h3">Locale Specific Marketing Info: {locale}</Header>

                    <Form.Group>
                        <Form.Input autoComplete="off" width={3} required label='Title' placeholder="Top Gun (3D)" value={selectedMarketingData.title} name="title" onChange={onChangeMarketingData.bind(this)} />
                    </Form.Group>

                    <Form.Group widths="equal">
                        <Form.TextArea autoComplete="off" required label='Description' value={selectedMarketingData.description} name="description" onChange={onChangeMarketingData.bind(this)} />
                    </Form.Group>

                    <Form.Group>
                        <Form.Dropdown search selection
                            width={3}
                            label='Preview/Trailer (Free Media Product)'
                            placeholder="Type a media product name or choose an option..."
                            icon='search'
                            loading={false}
                            size="small"
                            value={selectedMarketingData.trailer}
                            name="trailer"
                            closeOnChange
                            options={this.state.trailerOptions}
                            onChange={onChangeMarketingData.bind(this)} />
                    </Form.Group>


                    <Divider />

                    <Header as="h3">Unity Texture Images</Header>

                    <Message>
                        <p>Unity poster dimensions (width x height): 170x253</p>
                        <p>Unity background image dimensions (width x height): 907x679 on a 1024x1024 image (<a href="https://www.dropbox.com/s/z8hjla35noobmdr/Background_BigBuckBunny.png?raw=1">example</a>)</p>
                        <p>Unity screenshot image (width x height): 1920x800</p>
                    </Message>

                    {selectedMarketingData.unityPosterTexture &&
                        <Form.Group>
                            <Form.Input placeholder="Enter a url..."  autoComplete="off" width={8} required label='Unity Poster Image Texture' value={selectedMarketingData.unityPosterTexture.src} name="unityPosterTexture" onChange={onChangeImage.bind(this)} />
                            <Image src={selectedMarketingData.unityPosterTexture.src} floated="right" size="small" bordered />
                        </Form.Group>
                    }

                    {selectedMarketingData.unityPosterTexture &&
                        <Form.Group>
                            <Form.Input placeholder="Enter a url..." autoComplete="off" width={8} required label='Unity Background Image Texture' value={selectedMarketingData.unityBackgroundTexture.src} name="unityBackgroundTexture" onChange={onChangeImage.bind(this)} />
                            <Image src={selectedMarketingData.unityBackgroundTexture.src} floated="right" size="small" bordered />
                        </Form.Group>
                    }

                    <Form.Group>
                        <Form.Input placeholder="Enter a url..." autoComplete="off" width={8} required label='Unity Screenshot Image (1920x800px)' value={selectedMarketingData.screenshotImageUrl} name="screenshotImageUrl" onChange={onChangeMarketingData.bind(this)} />
                        <Image src={selectedMarketingData.screenshotImageUrl} floated="right" size="small" bordered />
                    </Form.Group>

                    <Divider />

                    <Header as="h3">Website Product Images</Header>

                    <Form.Group>
                        <Form.Input placeholder="Enter a url..."  autoComplete="off" width={8} required label='Poster Image' value={selectedMarketingData.posterImageUrl} name="posterImageUrl" onChange={onChangeMarketingData.bind(this)} />
                        <Image src={selectedMarketingData.posterImageUrl} floated="right" size="small" bordered />
                    </Form.Group>

                    <Form.Group>
                        <Form.Input placeholder="Enter a url..." autoComplete="off" width={8} required label='Background Image (1500-2000 by 900-1000px)' value={selectedMarketingData.backgroundImageUrl} name="backgroundImageUrl" onChange={onChangeMarketingData.bind(this)} />
                        <Image src={selectedMarketingData.backgroundImageUrl} floated="right" size="small" bordered />
                    </Form.Group>

                    <Form.Group>
                        <Form.Input placeholder="Enter a url..." autoComplete="off" width={8} required label='Hero Image (1000x600px)' value={selectedMarketingData.heroImageUrl} name="heroImageUrl" onChange={onChangeMarketingData.bind(this)} />
                        <Image src={selectedMarketingData.heroImageUrl} floated="right" size="small" bordered />
                    </Form.Group>

                    <Form.Group>
                        <Form.Input placeholder="Enter a url..."  autoComplete="off" width={8} required label='Logo Image (600px wide)' value={selectedMarketingData.logoImageUrl} name="logoImageUrl" onChange={onChangeMarketingData.bind(this)} />
                        <Image src={selectedMarketingData.logoImageUrl} floated="right" size="small" bordered />
                    </Form.Group>

                    <Divider />
                    <Header as="h4">Youtube Clip Info</Header>
                    <Form.Group>
                        <Form.Input autoComplete="off" width={4} label='Youtube Trailer Url' placeholder="Full youtube link here..." value={selectedMarketingData.trailerUrl} name="trailerUrl" onChange={onChangeMarketingData.bind(this)} />
                        <ReactPlayer url={selectedMarketingData.trailerUrl} playing width='300px' height='170px' controls muted />
                    </Form.Group>
                    <Form.Group>
                        <Form.Input autoComplete="off" width={4} label='Youtube Extra Clip Url' placeholder="Youtube clip url here..." value={selectedMarketingData.clipUrl} name="clipUrl" onChange={onChangeMarketingData.bind(this)} />
                        <ReactPlayer url={selectedMarketingData.clipUrl} playing width='300px' height='170px' controls muted />
                    </Form.Group>
                    <Form.Group>
                        <Form.Input placeholder="Enter a url..." autoComplete="off" width={8} required label='Trailer Website Image (600x300px)' value={selectedMarketingData.trailerImageUrl} name="trailerImageUrl" onChange={onChangeMarketingData.bind(this)} />
                        <Image src={selectedMarketingData.trailerImageUrl} floated="right" size="small" bordered />
                    </Form.Group>
                    <Form.Group>
                        <Form.Input placeholder="Enter a url..." autoComplete="off" width={8} required label='Clip website image (600x300px)' value={selectedMarketingData.clipImageUrl} name="clipImageUrl" onChange={onChangeMarketingData.bind(this)} />
                        <Image src={selectedMarketingData.clipImageUrl} floated="right" size="small" bordered />
                    </Form.Group>

                    <Divider />
                    <Header as="h4">Movie Info</Header>
                    <Form.Group>
                        <Form.Input autoComplete="off" width={5} label='Actors (Comma separated)' placeholder="Tom Cruise, Amy Adams" value={_.join(selectedMarketingData.actors, ", ")} name="actors" onChange={onChangeMarketingDataArray.bind(this)} />
                    </Form.Group>

                    <Form.Group>
                        <Form.Input autoComplete="off" width={5} label='Directors (Comma separated)' placeholder="Stanley Kubrick" value={_.join(selectedMarketingData.directors, ", ")} name="directors" onChange={onChangeMarketingDataArray.bind(this)} />
                    </Form.Group>

                    <Form.Group>
                        <Form.Input autoComplete="off" width={2} required label='Release Year' placeholder="2019" value={selectedMarketingData.releaseYear} name="releaseYear" onChange={onChangeMarketingData.bind(this)} />
                    </Form.Group>

                    <Form.Group>
                        <Form.Input autoComplete="off" width={5} label='Subtitle Languages (Comma separated)' value={_.join(selectedMarketingData.subtitles, ", ")} name="subtitles" onChange={onChangeMarketingDataArray.bind(this)} />
                    </Form.Group>

                    <Form.Group>
                        <Form.Input autoComplete="off" width={5} required label='Audio Track Languages (Comma separated)' value={_.join(selectedMarketingData.audioTracks, ", ")} name="audioTracks" onChange={onChangeMarketingDataArray.bind(this)} />
                    </Form.Group>

                    <Form.Group>
                        <Form.Input autoComplete="off" required width={2} placeholder="PG 13" label='Age Restriction or Content Rating (e.g. PG 13)' value={selectedMarketingData.ageRestriction} name="ageRestriction" onChange={onChangeMarketingData.bind(this)} />
                    </Form.Group>
                </div>
            );
        }

        // We have a different sku per location code.
        const pricing = (this.state.product.stripeProductData && this.state.product.stripeProductData.skus) && (
            <div>
                <Header as="h2">Pricing</Header>

                <Segment>
                    <Header as="h3">Stripe Product Info</Header>
                    <p><strong>Product ID: </strong> {this.state.product.stripeProductData.id}</p>
                    <p><strong>Active?: </strong> {this.state.product.stripeProductData.active ? "yes" : "no"}</p>
                    {!this.state.product.stripeProductData.active && (
                        <Button icon="stripe" color="orange" onClick={this.onActivate.bind(this)}>Activate Product</Button>
                    )}
                </Segment>

                <Header as="h3">Adding new Countries & Prices</Header>
                <p>To add new countries, <strong>first select a pricing profile</strong>.</p>
                <p>Then add one of the allowed countries. It will pre-fill the default currency and default price for that country, based on the profile.</p>

                <Grid>
                    <Grid.Column width={8}>
                        <Form.Field label="Select a Pricing Profile">
                        </Form.Field>
                        {constants.PricingProfileOptions.map(profile => {
                            return (
                                <Form.Field key={profile.value}>
                                    <Radio
                                        value={profile.value}
                                        label={profile.text}
                                        name="pricingProfileFilter"
                                        checked={this.state.product.pricingProfileFilter === profile.value}
                                        onChange={this.onChange.bind(this)}
                                    />
                                </Form.Field>);
                        })}
                    </Grid.Column>
                </Grid>

                <Header as="h3">Countries</Header>

                <Form.Group>
                    <Form.Dropdown
                    label="Available locations"
                    width={4}
                    placeholder="Type a country name..."
                    multiple
                    fluid
                    selection
                    search
                    closeOnChange
                    value={this.state.product.locationCodes}
                    name="locationCodes"
                    options={this.state.product.pricingProfileFilter ? constants.PricingProfiles[this.state.product.pricingProfileFilter] : constants.CountryOptions}
                    onChange={this.onChange.bind(this)} />
                </Form.Group>

                <Table celled striped compact>
                    <Table.Header>
                        <Table.Row>
                            <Table.HeaderCell collapsing></Table.HeaderCell>
                            <Table.HeaderCell collapsing>Country</Table.HeaderCell>
                            <Table.HeaderCell collapsing>Active?</Table.HeaderCell>
                            <Table.HeaderCell>Amount</Table.HeaderCell>
                        </Table.Row>
                    </Table.Header>
                    <Table.Body>

                {this.state.product.locationCodes.map((locationCode, locationCodeIndex) => {
                    const country = _.find(constants.CountryOptions, ["key", locationCode]);

                    const skuIndex = _.findIndex(this.state.product.stripeProductData.skus.data, (sku) => {
                        return (sku.attributes && sku.attributes.LocationCode && sku.attributes.LocationCode === locationCode);
                    });
                    const sku = this.state.product.stripeProductData.skus.data[skuIndex];
                    const currencyInfo = sku ? constants.Currencies[_.toUpper(sku.currency)] : null;

                    let pricingProfileCurrency, pricingProfilePrice = null;
                    // if the currency info hasn't been filled in, let's retreive the defaults from the Pricing Profiles
                    if(currencyInfo == null){
                        const pricingProfile  = _.find(constants.PricingProfiles[this.state.product.pricingProfileFilter], ["key", locationCode]);
                        if(pricingProfile){
                            pricingProfileCurrency = pricingProfile.currency != null ? pricingProfile.currency : null;
                            pricingProfilePrice = pricingProfile.price != null ? pricingProfile.price : null;
                        }
                    }

                    const onChangeCurrency = async (e, { name, value }) => {
                        e.preventDefault();
                        const locationSKUs = this.state.locationSKUs;
                        if (!locationSKUs[locationCode]) {
                            locationSKUs[locationCode] = {};
                        }
                        locationSKUs[locationCode].selectedCurrency = value;
                        this.setState({ locationSKUs });
                    }

                    const onChangeCurrencyAmount = async (e, { name, value }) => {
                        e.preventDefault();
                        const locationSKUs = this.state.locationSKUs;
                        if (!locationSKUs[locationCode]) {
                            locationSKUs[locationCode] = {};
                        }
                        locationSKUs[locationCode].selectedCurrencyAmount = value;
                        this.setState({ locationSKUs });
                    }

                    const onAddPricing = async (e, { name, value }) => {
                        e.preventDefault();

                        const locationSKUs = this.state.locationSKUs;
                        if (locationSKUs[locationCode]) {
                            const payload = {
                                locationCode,
                                currency: locationSKUs[locationCode].selectedCurrency,
                                price: locationSKUs[locationCode].selectedCurrencyAmount,
                            }

                            try {
                                // HACK HACK HACK
                                //
                                // Save the product first, to update any location changes, then post the sku, then reload it!
                                await this.onSaveProduct();
                                this.setState({ loading: true });
                                const res = await superagent.post(`/api/admin/media/product/${this.state.product.id}/sku`).send(payload).accept('json');
                                await this.reloadProduct();
                            } catch (e) {
                                this.setState({ messages: e.response.body, loading: false });
                            }

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

                    const onRemovePricing = async (e) => {
                        e.preventDefault();

                        let product = this.state.product;
                        product.stripeProductData.skus.data.splice(skuIndex, 1);
                        this.setState({ loading: true, product });

                        try {
                            const res = await superagent.delete(`/api/admin/media/product/${this.state.product.id}/sku/${sku.id}`);
                        } catch (e) {
                            this.setState({ messages: e.response.body, loading: false });
                        }

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

                    if (sku) {
                        return (
                            <Table.Row>
                                <Table.Cell collapsing>
                                    <Button onClick={onRemovePricing.bind(this)} size="small">Remove</Button>
                                </Table.Cell>
                                <Table.Cell collapsing>{country && country.text}</Table.Cell>
                                <Table.Cell collapsing><Label horizontal color={sku.active ? "green" : "red"}>{sku.active ? "Active" : "Inactive"}</Label></Table.Cell>
                                <Table.Cell>
                                    <Label color="blue">
                                        {(currencyInfo && currencyInfo.icon) ? <Icon name={currencyInfo.icon} /> : <Icon name="dollar" />}{sku.currency}
                                    </Label>
                                    <Label color="blue" basic>{formatPrice(sku.currency, sku.price)}</Label>
                                </Table.Cell>
                            </Table.Row>
                        );
                    } else {
                        const locationSKU = this.state.locationSKUs[locationCode];
                        return (
                            <Table.Row>
                                <Table.Cell collapsing></Table.Cell>
                                <Table.Cell collapsing>{country && country.text}</Table.Cell>
                                <Table.Cell collapsing></Table.Cell>
                                <Table.Cell>
                                    <Form.Group widths="equal">
                                        <Form.Dropdown
                                            placeholder="Type a currency name..."
                                            fluid
                                            selection
                                            search
                                            closeOnChange
                                            size="small"
                                            value={locationSKU ? locationSKU.selectedCurrency : pricingProfileCurrency }
                                            name="selectedCurrency"
                                            options={constants.CurrencyOptions}
                                            onChange={onChangeCurrency.bind(this)} />
                                        <Form.Input
                                            autoComplete="off"
                                            required
                                            placeholder="Amount in cents (e.g. enter 499 for $4.99)"
                                            value={locationSKU ? locationSKU.selectedCurrencyAmount : pricingProfilePrice }
                                            name="selectedCurrencyAmount"
                                            onChange={onChangeCurrencyAmount.bind(this)} />
                                        <Form.Button onClick={onAddPricing.bind(this)} >Add Pricing</Form.Button>
                                    </Form.Group>
                                </Table.Cell>
                            </Table.Row>
                        )
                    }
                })}
                </Table.Body>
                </Table>
            </div>
        );

        const panes = [
            { menuItem: 'Details', render: () => <Tab.Pane attached={false}>{existingProductInfo}<Divider />{basicProductInfo}</Tab.Pane> },
            { menuItem: 'Media Items', render: () => <Tab.Pane attached={false}>{mediaItems}</Tab.Pane> },
            { menuItem: 'Room Settings', render: () => <Tab.Pane attached={false}>{roomSettings}</Tab.Pane> },
            { menuItem: 'Movie Nights', render: () => <Tab.Pane attached={false}>{movieNightsInfo}</Tab.Pane> },
            { menuItem: 'Marketing', render: () => <Tab.Pane attached={false}>{marketingInfo}</Tab.Pane> }
        ];

        if (pricing) {
            panes.push({ menuItem: 'Pricing', render: () => <Tab.Pane attached={false}>{pricing}</Tab.Pane> });
        }

        const tabs = (
            <Tab menu={{ secondary: true, pointing: true }} panes={panes} />
        );


        let activateButton = null;
        if (this.state.product.id) {
            if (this.state.product.status === "DRAFT") {
                if (this.state.product.stripeProductData) {
                    if (!this.state.product.stripeProductData.active) {
                        activateButton = <Button onClick={this.onActivate.bind(this)}>Activate Now!</Button>;
                    }
                } else {
                    activateButton = <Button onClick={this.onActivate.bind(this)}>Activate Now!</Button>;
                }
            }
        }

        let activationStatus = <div />
        if (this.state.product.id) {
            if (this.state.product.mediaItemIds.length === 0) {
                activationStatus = (
                    <Segment inverted color="red"><Icon name="dont" />This product does not have any media items!</Segment>
                );
            } else if (this.state.product.status === "DRAFT") {
                activationStatus = (
                    <Segment inverted color="red"><Icon name="dont" />This is a DRAFT. {activateButton}</Segment>
                );
            } else if (this.state.product.status === "ACTIVATED") {
                activationStatus = (
                    <Segment inverted color="green"><Icon name="check circle" />Activated! You should be able to see this in Bigscreen!</Segment>
                );
            } else if (this.state.product.status === "DISABLED") {
                activationStatus = (
                    <Segment inverted color="black"><Icon name="dont" />This product is disabled</Segment>
                );
            }
        }

        let stripeActivationStatus = <div />
        if (this.state.product.id && this.state.product.stripeProductData && this.state.product.stripeProductData.skus) {
            if (this.state.product.stripeProductData.active) {
                stripeActivationStatus = (
                    <Segment inverted color="green"><Icon name="check circle" />Active on Stripe</Segment>
                );
            } else {
                stripeActivationStatus = (
                    <Segment inverted color="red"><Icon name="stripe" />Not active on Stripe! See "Pricing" tab to activated on Stripe.</Segment>
                );
            }
        }

        return (
            <MoviesTVWrapper loading={this.state.loading}>
                {(!this.state.product.id) && <Header as="h2">Create Media Product</Header>}
                {(this.state.product.id) && <Header as="h2">Edit Media Product</Header>}
                <Header as="h3">{this.state.product.title}</Header>

                {messages && messages}

                <Form size='small' onSubmit={this.onSaveProduct.bind(this)}>
                    {(!this.state.product.id) && basicProductInfo}

                    {activationStatus}
                    {stripeActivationStatus}

                    {(this.state.product.id) && tabs}

                    <Segment basic>
                        {(!this.state.product.id) && <Form.Group><Button primary content='Create product' type='submit' /></Form.Group>}
                        {(this.state.product.id) && <Form.Group><Button primary content='Save product' type='submit' /></Form.Group>}
                    </Segment>
                </Form>
            </MoviesTVWrapper>
        );
    }
}
