import React from 'react';
import superagent from 'superagent';
import { fromUnixTime } from "date-fns";
import { formatInTimeZone } from 'date-fns-tz';
import { Accordion, Segment, Header, Icon, Button, Table, Form, Label, Modal, Message, Card, Image, Radio, Grid, SegmentGroup } from 'semantic-ui-react'

import * as ApiUtils from '../CloudApi/ApiUtils.js';
import constants, { DEFAULT_TIMEZONE } from '../CloudApi/Constants.js';
import BigApiErrorMessage from '../CloudApi/BigApiErrorMessage.jsx';
import BigOrdersWrapper from './BigOrdersWrapper.jsx';
import BigOrderComponent from './BigOrderComponent.jsx';

export default class BigCreateCustomOrder extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            bigOrderSearchValue: "",
            shopifyProductKeys: [],
            sendEmail: true,
            priority: 55,
            scanRequestOption: "Unknown",
            ipdOverride: -1,
            convertToBigOrder: false,
            error: null
        };
    }

    async componentDidMount() {
        try {
            let schemas = await ApiUtils.getFabricatorSchemas();
            this.setState({ schemas });
        } catch (e) {
            console.error(e);
        }
    }

    async onFindBigOrders() {
        this.setState({ loading: true, error: null });

        let query = "";
        if (this.state.bigOrderSearchValue.startsWith("#BS")) {
            query = `/api/admin/shop/orders?origin=Shopify&limit=1&shopifyOrderName=${encodeURIComponent(this.state.bigOrderSearchValue)}`
        } else {
            // Assume it's an email
            query = `/api/admin/shop/orders?origin=Shopify&shopifyCustomerEmail=${encodeURIComponent(this.state.bigOrderSearchValue)}`
        }

        try {
            const res = await superagent.get(query).accept('json');
            console.log(res.body);
            if (res.body.items.length === 1) {
                this.setState({ bigOrders: res.body.items, selectedBigOrder: null });
            } else if (res.body.items.length > 1) {
                this.setState({ bigOrders: res.body.items, selectedBigOrder: null });
            } else {
                this.setState({ bigOrders: null, selectedBigOrder: null });
            }
        } catch (e) {
            this.setState({ error: e });
            console.error(e);
        }

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

    async onCreateReplacement(order) {
        this.setState({ selectedBigOrder: order, ipdOverride: order.ipd, bigscreenAccountId: order.ownerBigscreenAccountId });
    }

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

    async onCreateCustomOrder() {
        this.setState({ loading: true, error: null });

        try {
            const payload = {
                originalBigOrderId: this.state.selectedBigOrder.id,
                scanRequestAction: this.state.scanRequestOption,
                sendEmail: this.state.sendEmail,
                priority: this.state.priority,
                test: false
            };

            payload.shopifyProductIds = this.state.shopifyProductKeys.map((key) => this.state.schemas.ShopifyProductIds[key]);

            if (this.state.ipdOverride !== -1) {
                payload.ipd = this.state.ipdOverride;
            }

            let res = await superagent.post(`/api/admin/shop/shopify_order`).send(payload).accept('json');

            // Check for errors in the response (order created but with issues)
            if (res.body.errors && res.body.errors.length > 0) {
                const errorMessages = res.body.errors.map(e => e.message).join(', ');
                console.error("Order created with errors:", errorMessages);
                // Still redirect but with warning indication
                window.location.href = `/shop/order/${res.body.bigOrder.shopifyOrderName}?warning=${encodeURIComponent(errorMessages)}`;
            } else {
                window.location.href = `/shop/order/${res.body.bigOrder.shopifyOrderName}`;
            }
        } catch (e) {
            this.setState({ error: e });
            console.error(e);
        }

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

    onToggleProductSelection(productKey) {
        return (e) => {
            let shopifyProductKeys = this.state.shopifyProductKeys;
            if (shopifyProductKeys.includes(productKey)) {
                shopifyProductKeys = shopifyProductKeys.filter((id) => id !== productKey);
            } else {
                shopifyProductKeys.push(productKey);
            }
            this.setState({ shopifyProductKeys });
        }
    }

    renderProductCheckbox(productKey) {
        let cardColor = "";
        let inverted = true;
        if (this.state.shopifyProductKeys.includes(productKey)) {
            cardColor = "green";
            inverted = false;
        }

        let productType = productKey;

        return (
            <SegmentGroup>
                <Segment disabled={inverted} color={cardColor} clearing>
                    <Header as="h3">
                        {this.state.shopifyProductKeys.includes(productKey) && <><Icon name="check circle" color="green" />&nbsp;</>}
                        {ApiUtils.splitUpperCamelCase(productKey)}
                    </Header>
                    <Table basic='very' striped celled compact>
                        <Table.Body>
                            <Table.Row>
                                <Table.Cell collapsing>
                                    <Image size='small' floated='left' src={`/images/${productType}.png`} />
                                </Table.Cell>
                                <Table.Cell verticalAlign='top'>
                                    {this.state.shopifyProductKeys.includes(productKey) && (
                                        <Message floated="right" icon inverted color="green">
                                            <Icon name="check circle" />
                                            <Message.Content><Message.Header as="h2">Added to order</Message.Header>
                                            </Message.Content>
                                        </Message>
                                    )}
                                    {this.state.shopifyProductKeys.includes(productKey) && productType == "ReplacementBigscreenBeyondV1" && (
                                        <Form.Group>
                                            <Form.Select
                                                label='IPD Override'
                                                name="ipdOverride"
                                                value={this.state.ipdOverride}
                                                options={this.state.schemas.IpdOptions}
                                                onChange={this.onChange.bind(this)}
                                            />
                                        </Form.Group>
                                    )}
                                </Table.Cell>
                            </Table.Row>
                        </Table.Body>
                    </Table>
                </Segment>
                <Segment clearing>
                    {this.state.shopifyProductKeys.includes(productKey) && <Button floated='left' onClick={this.onToggleProductSelection(productKey).bind(this)}>Remove from order</Button>}
                    {!this.state.shopifyProductKeys.includes(productKey) && <Button floated='right' primary onClick={this.onToggleProductSelection(productKey).bind(this)}>Add to order</Button>}
                </Segment>
            </SegmentGroup>
        )
    }

    render() {
        if (!this.state.schemas) {
            return <BigOrdersWrapper title="Create Replacement Order"><Segment basic><Icon loading name='circle notch' />Loading...</Segment></BigOrdersWrapper>;
        }

        let createButtonDisabled = true;
        if (this.state.shopifyProductKeys.length > 0) {
            if (this.state.shopifyProductKeys.includes("ReplacementBeyondCushionV1")) {
                createButtonDisabled = this.state.scanRequestOption === "Unknown";
            } else {
                createButtonDisabled = false;
            }
        }

        let customOrderForm = null;
        if (this.state.selectedBigOrder) {
            customOrderForm = (
                <Segment>
                    <Header as="h2">2. Create Replacement Order</Header>
                    <BigApiErrorMessage error={this.state.error} />
                    <Form size='small' loading={this.state.loading}>
                        <Segment>
                            <Header >Add Items ({`${this.state.shopifyProductKeys.length} items added`})</Header>
                            <Grid columns={3}>
                                <Grid.Row>
                                    <Grid.Column>
                                        {this.renderProductCheckbox("ReplacementBeyondCushionV1")}
                                    </Grid.Column>

                                    <Grid.Column>
                                        {this.renderProductCheckbox("ReplacementBigscreenBeyondV1")}
                                    </Grid.Column>

                                    <Grid.Column>
                                        {this.renderProductCheckbox("BeyondCyberboxV1")}
                                    </Grid.Column>
                                </Grid.Row>

                                <Grid.Row>
                                    <Grid.Column>
                                        {this.renderProductCheckbox("ReplacementBeyondFibreOpticCableV1")}
                                    </Grid.Column>

                                    <Grid.Column>
                                        {this.renderProductCheckbox("ReplacementBeyondLinkBoxV1")}
                                    </Grid.Column>

                                    <Grid.Column>
                                        {this.renderProductCheckbox("ReplacementBeyondSoftStrapV1")}
                                    </Grid.Column>
                                </Grid.Row>

                                <Grid.Row>
                                    <Grid.Column>
                                        {this.renderProductCheckbox("IPDDiscoveryUnitV1")}
                                    </Grid.Column>
                                </Grid.Row>
                            </Grid>
                        </Segment>

                        {this.state.shopifyProductKeys.includes("ReplacementBeyondCushionV1") && <Segment>
                            <Header>Scan Request Action</Header>
                            <Form.Group>
                                <Radio toggle
                                    label='Create a new scan request and email it to the user'
                                    name='scanRequestOption'
                                    value={this.state.schemas.BigOrderScanRequestActions["CreateNewScanRequest"]}
                                    checked={this.state.scanRequestOption === this.state.schemas.BigOrderScanRequestActions["CreateNewScanRequest"]}
                                    onChange={this.onChange.bind(this)}
                                />
                            </Form.Group>

                            <Form.Group>
                                <Radio toggle
                                    label='Use the scan request from the original Big Order (customer will NOT receive a new scan request email)'
                                    name='scanRequestOption'
                                    value={this.state.schemas.BigOrderScanRequestActions["DuplicateMostRecentScanRequest"]}
                                    checked={this.state.scanRequestOption === this.state.schemas.BigOrderScanRequestActions["DuplicateMostRecentScanRequest"]}
                                    onChange={this.onChange.bind(this)}
                                />
                            </Form.Group>
                        </Segment>}

                        <Form.Group widths="1">
                            <Form.Input required label='Priority' value={this.state.priority} name="priority" onChange={this.onChange.bind(this)} />
                        </Form.Group>

                        <Button disabled={createButtonDisabled} fluid primary content='Create this order' type='button' onClick={this.onCreateCustomOrder.bind(this)} />
                    </Form>
                </Segment>
            );
        }

        return (
            <BigOrdersWrapper title="Create Replacement Order">
                <Segment>
                    <Header as="h2">1. Find an existing Big Order</Header>
                    <Form size='small' loading={this.state.loading}>
                        <Form.Group>
                            <Form.Input width={4} inline required label='Big Order # or Customer Email' value={this.state.bigOrderSearchValue} name="bigOrderSearchValue" onChange={this.onChange.bind(this)} />
                            <Form.Button primary content='Go' type='button' onClick={this.onFindBigOrders.bind(this)} />
                        </Form.Group>
                    </Form>

                    {(this.state.bigOrders && this.state.bigOrders.length > 0) &&
                        <Table celled striped compact>
                            <Table.Body>
                                {this.state.bigOrders.map(order => (
                                    <Table.Row>
                                        <Table.Cell collapsing>
                                            <Button primary onClick={this.onCreateReplacement.bind(this, order)}>Create Replacement</Button>
                                        </Table.Cell>
                                        <Table.Cell>
                                            <BigOrderComponent schemas={this.props.schemas} asTableRow={true} key={order.id} bigOrder={order} showDetail={false} allowClicks={false} />
                                        </Table.Cell>
                                    </Table.Row>
                                ))}
                            </Table.Body>
                        </Table>
                    }
                </Segment>

                {customOrderForm}
            </BigOrdersWrapper>
        );
    }
}
