import React from 'react';
import superagent from 'superagent';
import { fromUnixTime } from "date-fns";
import { formatInTimeZone } from 'date-fns-tz';
import { Segment, Header, Icon, Button, Table, Form, Label, Modal, Message, Card, Image, Radio, Grid, Step, Divider } 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 BigCreateCustomOrder2 extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            shopifyVariantIds: [],
            customerName: null,
            ownerBigscreenAccountId: null,
            sendEmail: true,
            priority: 55,
            scanRequestAction: "Unknown",
            showScanRequestModal: false,
            testOrder: true,
            ipdOverride: -1,
            convertToBigOrder: false,
            searchPerformed: false,
            error: null
        };
    }

    async componentDidMount() {
        try {
            this.setState({ loading: true });
            let schemas = await ApiUtils.getFabricatorSchemas();
            const res = await superagent.get(`/api/admin/shop/products`);

            this.setState({ schemas, products: res.body, productsCount: res.body.length });
        } catch (e) {
            console.error(e);
        }

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

    async onCreateReplacement(order) {
        this.setState({ bigscreenAccountId: order.ownerBigscreenAccountId });
    }

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

    async onFindCustomer() {
        this.setState({ loading: true, error: null, searchPerformed: false });

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

        try {
            const res = await superagent.get(query).accept('json');
            console.log(res.body);
            if (res.body.items.length > 0) {
                // Load the customer account info.
                const ownerBigscreenAccountId = res.body.items[0].ownerBigscreenAccountId;

                this.setState({ customerName: res.body.items[0].shopifyOrderSnapshot.shipping_address.name, ownerBigscreenAccountId });
            } else {
                this.setState({ customerName: null, ownerBigscreenAccountId: null });
            }
        } catch (e) {
            this.setState({ error: e });
            console.error(e);
        }

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

    getFilteredVariants() {
        if (!this.state.products) return [];

        const variants = [];
        for (const product of this.state.products) {
            for (const variant of product.variants) {
                if (variant.sku && variant.sku !== "BS2S-UP" && (variant.sku.startsWith("BS2S") || variant.sku.startsWith("CB") || variant.sku.startsWith("RB"))) {
                    let imageSrc = product.image ? product.image.src : null;
                    const variantImage = product.images.find(image => image.id === variant.image_id);
                    if (variantImage) {
                        imageSrc = variantImage.src;
                    }
                    variants.push({ product, variant, imageSrc });
                }
            }
        }
        return variants;
    }

    hasCushionSelected() {
        if (!this.state.products) return false;

        const filtered = this.getFilteredVariants();
        return this.state.shopifyVariantIds.some(id => {
            const match = filtered.find(f => f.variant.id === id);
            return match && match.variant.sku === "RBS1F";
        });
    }

    hasCourtesyHeadsetSelected() {
        if (!this.state.products) return false;

        const filtered = this.getFilteredVariants();
        return this.state.shopifyVariantIds.some(id => {
            const match = filtered.find(f => f.variant.id === id);
            return match && (match.variant.sku === "CBS2" || match.variant.sku === "CBS2E");
        });
    }

    hasShellSelected() {
        if (!this.state.products) return false;

        const filtered = this.getFilteredVariants();
        return this.state.shopifyVariantIds.some(id => {
            const match = filtered.find(f => f.variant.id === id);
            return match && match.variant.sku && match.variant.sku.startsWith("BS2S-");
        });
    }

    needsShellWarning() {
        return this.hasCourtesyHeadsetSelected() && !this.hasShellSelected();
    }

    openScanRequestModal() {
        this.setState({ showScanRequestModal: true });
    }

    closeScanRequestModal() {
        this.setState({ showScanRequestModal: false });
    }

    onToggleVariantSelection(productKey) {
        return (e) => {
            let shopifyVariantIds = [...this.state.shopifyVariantIds];
            if (shopifyVariantIds.includes(productKey)) {
                shopifyVariantIds = shopifyVariantIds.filter((id) => id !== productKey);
            } else {
                shopifyVariantIds.push(productKey);
            }

            const newState = { shopifyVariantIds };

            // Check if a cushion variant was just toggled on - open modal
            if (!this.state.shopifyVariantIds.includes(productKey) && shopifyVariantIds.includes(productKey)) {
                const filtered = this.getFilteredVariants();
                const match = filtered.find(f => f.variant.id === productKey);
                if (match && match.variant.sku === "RBS1F") {
                    newState.showScanRequestModal = true;
                }
            }

            this.setState(newState);
        }
    }

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

        try {
            const payload = {
                ownerBigscreenAccountId: this.state.ownerBigscreenAccountId,
                shopifyVariants: this.state.shopifyVariantIds,
                scanRequestAction: this.state.scanRequestAction,
                sendEmail: this.state.sendEmail,
                priority: this.state.priority,
                shopifyOrderMode: this.state.testOrder ? "TestOrder" : "ProductionOrder"
            };

            console.log(payload);

            let res = await superagent.post(`/api/admin/shop/shopify_order_2`).send(payload).accept('json');
            console.log(res.body);
            window.location.href = `/shop/order/${res.body.bigOrder.shopifyOrderName}`;
        } catch (e) {
            this.setState({ error: e });
            console.error(e);
        }

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

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

        const customerSelected = !!(this.state.customerName && this.state.customerName.length > 0 && this.state.ownerBigscreenAccountId);

        let createButtonDisabled = true;
        if (this.state.shopifyVariantIds.length > 0 && customerSelected) {
            if (this.hasCushionSelected()) {
                createButtonDisabled = this.state.scanRequestAction === "Unknown";
            } else {
                createButtonDisabled = false;
            }
        }
        if (this.needsShellWarning()) {
            createButtonDisabled = true;
        }

        const filteredVariants = this.getFilteredVariants();

        let customOrderForm = null;
        if (this.state.products) {
            customOrderForm = (
                <>
                    <Segment>
                        <Header>Add Items</Header>
                        <div style={!customerSelected ? { opacity: 0.45, pointerEvents: 'none' } : {}}>
                            <Card.Group itemsPerRow={2}>
                                {filteredVariants.map(({ product, variant, imageSrc }) => {
                                    const isSelected = this.state.shopifyVariantIds.includes(variant.id);
                                    return (
                                        <Card key={variant.id} color={isSelected ? "green" : "grey"} raised={isSelected}>
                                            {imageSrc && (
                                                <div style={{ height: '140px', display: 'flex', alignItems: 'center', justifyContent: 'center', backgroundColor: '#f5f5f5' }}>
                                                    <Image src={imageSrc} style={{ maxHeight: '140px', width: 'auto', objectFit: 'contain' }} />
                                                </div>
                                            )}
                                            <Card.Content>
                                                <Card.Header>{product.title}</Card.Header>
                                                <Card.Meta>{variant.title}</Card.Meta>
                                                <Card.Description>
                                                    <Label size="small">{variant.sku}</Label>
                                                </Card.Description>
                                            </Card.Content>
                                            <Card.Content extra>
                                                {isSelected ? (
                                                    <Button fluid basic color="red" icon="remove" content="Remove" onClick={this.onToggleVariantSelection(variant.id).bind(this)} />
                                                ) : (
                                                    <Button fluid primary icon="add" content="Add to order" onClick={this.onToggleVariantSelection(variant.id).bind(this)} />
                                                )}
                                            </Card.Content>
                                        </Card>
                                    );
                                })}
                            </Card.Group>
                        </div>
                    </Segment>

                    {/* Scan Request Modal */}
                    <Modal dimmer="blurring" open={this.state.showScanRequestModal} onClose={this.closeScanRequestModal.bind(this)}>
                        <Modal.Header>Scan Request Action</Modal.Header>
                        <Modal.Content>
                            <p>A cushion item has been added. Please select what to do with the scan request:</p>
                            <Form.Group>
                                <Radio toggle
                                    label='Create a new scan request and email it to the user'
                                    name='scanRequestAction'
                                    value={this.state.schemas.BigOrderScanRequestActions["CreateNewScanRequest"]}
                                    checked={this.state.scanRequestAction === this.state.schemas.BigOrderScanRequestActions["CreateNewScanRequest"]}
                                    onChange={this.onChange.bind(this)}
                                />
                            </Form.Group>
                            <br />
                            <Form.Group>
                                <Radio toggle
                                    label='Use the scan request from the original Big Order (customer will NOT receive a new scan request email)'
                                    name='scanRequestAction'
                                    value={this.state.schemas.BigOrderScanRequestActions["DuplicateMostRecentScanRequest"]}
                                    checked={this.state.scanRequestAction === this.state.schemas.BigOrderScanRequestActions["DuplicateMostRecentScanRequest"]}
                                    onChange={this.onChange.bind(this)}
                                />
                            </Form.Group>
                        </Modal.Content>
                        <Modal.Actions>
                            <Button primary onClick={this.closeScanRequestModal.bind(this)} disabled={this.state.scanRequestAction === "Unknown"}>
                                Confirm
                            </Button>
                        </Modal.Actions>
                    </Modal>
                </>
            );
        }

        const cartColumn = (
            <Segment style={{ position: 'sticky', top: '20px' }}>
                <Header as="h3">
                    <Icon name="shopping cart" />
                    <Header.Content>
                        Order Summary
                        <Header.Subheader>
                            {this.state.shopifyVariantIds.length} item{this.state.shopifyVariantIds.length !== 1 ? 's' : ''}
                        </Header.Subheader>
                    </Header.Content>
                </Header>

                <Divider />

                {this.state.shopifyVariantIds.length === 0 ? (
                    <Segment placeholder textAlign="center">
                        <Header icon>
                            <Icon name="shopping cart" />
                            No items added yet
                        </Header>
                    </Segment>
                ) : (
                    <div>
                        {this.state.shopifyVariantIds.map((id, index) => {
                            const match = filteredVariants.find(f => f.variant.id === id);
                            if (!match) return null;
                            return (
                                <React.Fragment key={id}>
                                    {index > 0 && <Divider fitted />}
                                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', padding: '8px 0' }}>
                                        <div>
                                            <strong>{match.product.title}</strong>
                                            <div style={{ color: '#666' }}>{match.variant.title}</div>
                                            <div style={{ color: '#999', fontSize: '0.85em' }}>SKU: {match.variant.sku}</div>
                                        </div>
                                        <Button icon="close" size="mini" basic color="red" onClick={this.onToggleVariantSelection(id).bind(this)} />
                                    </div>
                                </React.Fragment>
                            );
                        })}
                    </div>
                )}

                {this.hasCushionSelected() && (
                    <>
                        <Divider />
                        <Header as="h5">Scan Request Action</Header>
                        <div style={{ marginBottom: '10px' }}>
                            {this.state.scanRequestAction === "Unknown" ? (
                                <Label color="red" size="small">
                                    <Icon name="warning" /> Not selected
                                </Label>
                            ) : (
                                <Label color="green" size="small">
                                    <Icon name="check" /> {this.state.scanRequestAction}
                                </Label>
                            )}
                            {' '}
                            <Button size="mini" onClick={this.openScanRequestModal.bind(this)}>Change</Button>
                        </div>
                    </>
                )}

                <Divider />

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

                {this.needsShellWarning() && (
                    <Message warning icon size="small">
                        <Icon name="warning sign" />
                        <Message.Content>
                            <Message.Header>Shell color required</Message.Header>
                            Add a shell color (BS2S-C, BS2S-B, BS2S-O, or BS2S-P) to this order.
                        </Message.Content>
                    </Message>
                )}

                <BigApiErrorMessage error={this.state.error} />

                <Divider />

                <Header as="h5">Order Mode</Header>
                <div style={{ display: 'flex', flexDirection: 'column', gap: '12px', marginBottom: '16px' }}>
                    <Radio
                        toggle
                        label="Test Order"
                        checked={this.state.testOrder}
                        onChange={() => this.setState({ testOrder: true })}
                        style={{ color: '#fff' }}
                    />
                    <Radio
                        toggle
                        label="Production Order"
                        checked={!this.state.testOrder}
                        onChange={() => this.setState({ testOrder: false })}
                        style={{ color: '#fff' }}
                    />
                </div>
                {this.state.testOrder && (
                    <Message warning icon size="small" style={{ marginBottom: '16px' }}>
                        <Icon name="dont" />
                        <Message.Content>
                            <Message.Header>Test Order</Message.Header>
                            This is a test order. BE CAREFUL WITH SHIPPING THIS ORDER!
                        </Message.Content>
                    </Message>
                )}

                <Button disabled={createButtonDisabled || this.state.loading} loading={this.state.loading} fluid primary size="large" icon="cart" content='Create this order' type='button' onClick={this.onCreateCustomOrder.bind(this)} />
            </Segment>
        );

        return (
            <BigOrdersWrapper title="Create Replacement Order">
                {/* Step progress indicator */}
                <Step.Group ordered fluid size="small">
                    <Step completed={customerSelected} active={!customerSelected}>
                        <Step.Content>
                            <Step.Title>Find Customer</Step.Title>
                            <Step.Description>Search by order # or email</Step.Description>
                        </Step.Content>
                    </Step>
                    <Step active={customerSelected} disabled={!customerSelected}>
                        <Step.Content>
                            <Step.Title>Create Order</Step.Title>
                            <Step.Description>Select items and submit</Step.Description>
                        </Step.Content>
                    </Step>
                </Step.Group>

                <Segment>
                    <Form size='small' loading={this.state.loading}>
                        <Form.Group>
                            <Form.Input width={4} inline required label='Enter Shopify Order #, Big Order # or Customer Email' value={this.state.customerSearchValue} name="customerSearchValue" onChange={this.onChange.bind(this)} />
                            <Form.Button primary content='Go' type='button' onClick={this.onFindCustomer.bind(this)} />
                        </Form.Group>
                    </Form>

                    {customerSelected && (
                        <Segment inverted color="blue">
                            <Header as="h2" inverted>
                                <Icon name="user" />
                                <Header.Content>
                                    {this.state.customerName}
                                    <Header.Subheader style={{ color: 'rgba(255,255,255,0.8)' }}>
                                        Account ID: {this.state.ownerBigscreenAccountId}
                                    </Header.Subheader>
                                </Header.Content>
                            </Header>
                        </Segment>
                    )}
                    {(this.state.searchPerformed && this.state.customerName === null && this.state.ownerBigscreenAccountId === null) && (
                        <Message warning>No customer found.</Message>
                    )}
                </Segment>

                {customerSelected && (
                    <Grid>
                        <Grid.Column width={11}>
                            {customOrderForm}
                        </Grid.Column>

                        <Grid.Column width={5}>
                            {cartColumn}
                        </Grid.Column>
                    </Grid>
                )}
            </BigOrdersWrapper>
        );
    }
}
