import React from 'react';
import superagent from 'superagent';
import cookie, { load } from 'react-cookies';

import constants, { DEFAULT_TIMEZONE } from '../CloudApi/Constants.js';
import { Segment, Form, Button, Icon, Pagination, Label, FormField, Grid, List, Header } from 'semantic-ui-react';
import { DateInput } from 'semantic-ui-calendar-react';

import * as ApiUtils from '../CloudApi/ApiUtils.js';

const RECENTS_STORAGE_KEY = "bigorders_query_full_recents";
const MAX_RECENTS = 5;

export default class BigOrdersQuery extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            query: {
                origin: "Shopify"
            },
            limit: props.limit || 50,
            offset: 0,
            loading: true,
            recents: []
        };
    }

    loadRecentsFromStorage() {
        try {
            const stored = localStorage.getItem(RECENTS_STORAGE_KEY);
            if (stored) {
                return JSON.parse(stored);
            }
        } catch (e) {
            console.log("Error loading recents from storage:", e);
        }
        return [];
    }

    saveRecentsToStorage(recents) {
        try {
            localStorage.setItem(RECENTS_STORAGE_KEY, JSON.stringify(recents));
        } catch (e) {
            console.log("Error saving recents to storage:", e);
        }
    }

    generateRecentName(query, shopifySchemas) {
        const parts = [];

        // Add date range if present
        if (query.shopifyMinCreatedAt || query.shopifyMaxCreatedAt) {
            const formatDate = (dateStr) => {
                if (!dateStr) return null;
                const date = new Date(dateStr);
                return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
            };
            const minDate = formatDate(query.shopifyMinCreatedAt);
            const maxDate = formatDate(query.shopifyMaxCreatedAt);
            if (minDate && maxDate) {
                parts.push(`${minDate} - ${maxDate}`);
            } else if (minDate) {
                parts.push(`After ${minDate}`);
            } else if (maxDate) {
                parts.push(`Before ${maxDate}`);
            }
        }

        // Add state if present
        if (query.state) {
            parts.push(query.state);
        }

        // Add country if present
        if (query.countryCode) {
            const country = constants.CountryOptions2.find(c => c.value === query.countryCode.toUpperCase());
            parts.push(country ? country.text : query.countryCode);
        }

        // Add origin if not default
        if (query.origin && query.origin !== "Shopify") {
            parts.push(query.origin);
        }

        // Add IPD if present
        if (query.ipd) {
            parts.push(`IPD: ${query.ipd}`);
        }

        // Add product variants if present
        if (query.shopifyVariantIds && query.shopifyVariantIds.length > 0 && shopifySchemas) {
            const variantNames = query.shopifyVariantIds.map(id => {
                const variant = shopifySchemas.productVariants.find(v => v.value === id);
                return variant ? variant.text : id;
            });
            if (variantNames.length === 1) {
                parts.push(variantNames[0]);
            } else {
                parts.push(`${variantNames.length} variants`);
            }
        }

        // Add email if present
        if (query.shopifyCustomerEmail) {
            parts.push(query.shopifyCustomerEmail);
        }

        // Add order number if present
        if (query.shopifyOrderName) {
            parts.push(`#${query.shopifyOrderName}`);
        }

        if (parts.length === 0) {
            return "All orders";
        }

        return parts.slice(0, 3).join(" · ") + (parts.length > 3 ? " ..." : "");
    }

    generateRecentDescription(query) {
        const details = [];

        if (query.minPriority) {
            details.push(`Priority ≥${query.minPriority}`);
        }

        if (query.shopifyVariantIds && query.shopifyVariantIds.length > 1) {
            details.push(`${query.shopifyVariantIds.length} product variants`);
        }

        return details.join(", ");
    }

    addToRecents(query) {
        // Don't save empty queries
        const hasFilters = Object.keys(query).some(key =>
            key !== "origin" && query[key] && (Array.isArray(query[key]) ? query[key].length > 0 : true)
        );
        if (!hasFilters) return;

        const name = this.generateRecentName(query, this.state.shopifySchemas);
        const description = this.generateRecentDescription(query);
        const newRecent = {
            id: Date.now(),
            name,
            description,
            query: { ...query },
            timestamp: new Date().toISOString()
        };

        // Remove duplicates (same query params)
        const queryKey = JSON.stringify(Object.keys(query).sort().reduce((obj, key) => {
            obj[key] = query[key];
            return obj;
        }, {}));

        let recents = this.state.recents.filter(r => {
            const rKey = JSON.stringify(Object.keys(r.query).sort().reduce((obj, key) => {
                obj[key] = r.query[key];
                return obj;
            }, {}));
            return rKey !== queryKey;
        });

        recents.unshift(newRecent);
        recents = recents.slice(0, MAX_RECENTS);

        this.setState({ recents });
        this.saveRecentsToStorage(recents);
    }

    removeFromRecents(recentId) {
        const recents = this.state.recents.filter(r => r.id !== recentId);
        this.setState({ recents });
        this.saveRecentsToStorage(recents);
    }

    loadRecentQuery(recent) {
        const query = { ...recent.query };

        this.setState({ query }, async () => {
            const params = this.getUrlSearchParams();
            const newPathQuery = `${window.location.pathname}?${params.toString()}`;
            window.history.pushState(null, '', newPathQuery);
            await this.props.onQueryUpdated(params);
        });
    }

    async componentDidMount() {
        try {
            const shopifySchemas = await ApiUtils.getShopifySchemas();
            const recents = this.loadRecentsFromStorage();

            const params = new URLSearchParams(window.location.search);
            const query = {};
            for (const [key, value] of params.entries()) {
                if (key === "limit") {
                    this.setState({ limit: value });
                } else if (key === "offset") {
                    this.setState({ offset: value });
                } else if (key === "shopifyProductIds") {
                    query[key] = value.split(",");
                } else {
                    query[key] = value;
                }
            }
            console.log(query);
            this.setState({ query, shopifySchemas, recents, loading: false });

            params.append("limit", this.state.limit);
            await this.props.onQueryUpdated(params);

            // Don't add to recents on initial page load - only when user makes changes
        } catch (e) {
            console.log(e);
        }
    }

    getUrlSearchParams() {
        const queryString = new URLSearchParams();

        if (this.state.query) {
            for (const [key, value] of Object.entries(this.state.query)) {
                if (value === "" || value === null) continue;
                queryString.append(key, value);
            }
        }
        queryString.append("limit", this.state.limit);

        if (this.props.offset) {
            queryString.append("offset", this.props.offset);
        }

        return queryString;
    }

    onChange(e, { name, value }) {
        const query = this.state.query;

        if (value === "" || value === null) {
            console.log("delete", name, value);
            delete query[name];
        } else {
            if (name === "state" && value === ApiUtils.ANY_VALUE) {
                delete query["state"];
            } else if (name === "shopifyMinCreatedAt") {
                console.log(ApiUtils.CovertDateTimeToShopify(value));
                query["shopifyMinCreatedAt"] = ApiUtils.CovertDateTimeToShopify(value);
            } else if (name === "shopifyMaxCreatedAt") {
                console.log(ApiUtils.CovertDateTimeToShopify(value));
                query["shopifyMaxCreatedAt"] = ApiUtils.CovertDateTimeToShopify(value);
            } else if (name === "shopifyProductIds") {
                const currentProductIds = query["shopifyProductIds"] || [];
                if (currentProductIds.includes(value)) {
                    currentProductIds.splice(currentProductIds.indexOf(value), 1);
                } else {
                    currentProductIds.push(value);
                }
                query["shopifyProductIds"] = currentProductIds;
            } else {
                query[name] = value;
            }
        }

        this.setState({ query }, async () => {
            const params = this.getUrlSearchParams();
            console.log(params.toString());
            const newPathQuery = `${window.location.pathname}?${params.toString()}`;
            window.history.pushState(null, '', newPathQuery);
            await this.props.onQueryUpdated(params);

            // Save to recents after query executes
            this.addToRecents(this.state.query);
        });
    }

    onClearValue(e, { name, value }) {
        const query = this.state.query;
        query[name] = "";
        this.setState({ query }, this.onChange(e, {}));
    }

    render() {
        if (!this.props.schemas) return null;
        if (this.state.loading) {
            return false;
        }

        return (
            <Grid>
                {/* Main Query Form */}
                <Grid.Column width={13}>
                    <Segment secondary loading={this.state.loading}>
                        <Form size='small'>
                            <Form.Group widths="equal">
                                <DateInput
                                    name="shopifyMinCreatedAt"
                                    autoComplete="off"
                                    dateFormat='LL'
                                    clearable
                                    closable
                                    placeholder="Created After"
                                    value={new Date(this.state.query.shopifyMinCreatedAt)}
                                    iconPosition="left"
                                    onChange={this.onChange.bind(this)} />
                                <DateInput
                                    name="shopifyMaxCreatedAt"
                                    autoComplete="off"
                                    dateFormat='LL'
                                    clearable
                                    closable
                                    placeholder="Created Before"
                                    value={new Date(this.state.query.shopifyMaxCreatedAt)}
                                    iconPosition="left"
                                    onChange={this.onChange.bind(this)} />
                                <Form.Input
                                    placeholder="Shopify #"
                                    name="shopifyOrderName"
                                    icon={
                                        this.state.query.shopifyOrderName && <Icon name="delete" link onClick={this.onClearValue.bind(this, null, { name: "shopifyOrderName", value: null })} />
                                    }
                                    value={this.state.query.shopifyOrderName}
                                    onChange={this.onChange.bind(this)}
                                />
                                <Form.Input
                                    placeholder="Shopify Email"
                                    name="shopifyCustomerEmail"
                                    icon={
                                        this.state.query.shopifyCustomerEmail && <Icon name="delete" link onClick={this.onClearValue.bind(this, null, { name: "shopifyCustomerEmail", value: null })} />
                                    }
                                    value={this.state.query.shopifyCustomerEmail}
                                    onChange={this.onChange.bind(this)}
                                />

                            </Form.Group>
                            <Form.Group>
                                <Form.Select
                                    width={2}
                                    clearable
                                    label='State'
                                    name="state"
                                    value={this.state.query.state}
                                    options={this.props.schemas.BigOrderStateOptions}
                                    onChange={this.onChange.bind(this)}
                                />
                                <Form.Input
                                    width={2}
                                    placeholder="(0-100)"
                                    label="Min&nbsp;Priority"
                                    name="minPriority"
                                    icon={
                                        this.state.query.minPriority && <Icon name="delete" link onClick={this.onClearValue.bind(this, null, { name: "minPriority", value: null })} />
                                    }
                                    value={this.state.query.minPriority}
                                    onChange={this.onChange.bind(this)}
                                />
                                <Form.Select
                                    width={2}
                                    clearable
                                    label='IPD'
                                    name="ipd"
                                    value={this.state.query.ipd}
                                    options={this.props.schemas.IpdOptions}
                                    onChange={this.onChange.bind(this)}
                                />
                                <Form.Select
                                    width={2}
                                    clearable
                                    label="Origin"
                                    name="origin"
                                    value={this.state.query.origin}
                                    options={this.props.schemas.BigOrderOriginOptions}
                                    onChange={this.onChange.bind(this)}
                                />
                                <Form.Select
                                    width={3}
                                    clearable
                                    label="Country"
                                    search
                                    closeOnChange
                                    name="countryCode"
                                    value={_.toUpper(this.state.query.countryCode)}
                                    options={constants.CountryOptions2}
                                    onChange={this.onChange.bind(this)}
                                />
                                <Form.Dropdown
                                    width={5}
                                    label="Filter by product variant"
                                    placeholder="Product Variant"
                                    multiple
                                    selection
                                    search
                                    fluid
                                    value={this.state.query.shopifyVariantIds}
                                    name="shopifyVariantIds"
                                    options={this.state.shopifySchemas.productVariants}
                                    onChange={this.onChange.bind(this)}
                                />
                            </Form.Group>
                        </Form>
                    </Segment>
                </Grid.Column>

                {/* Recents Sidebar */}
                <Grid.Column width={3}>
                    <Segment>
                        <Header as="h5" style={{ marginBottom: '0.5em' }}>
                            <Icon name="history" />
                            Recent Queries
                        </Header>
                        {this.state.recents.length === 0 ? (
                            <p style={{ color: '#888', fontSize: '0.9em' }}>No recent queries</p>
                        ) : (
                            <List divided relaxed size="small">
                                {this.state.recents.map(recent => (
                                    <List.Item key={recent.id}>
                                        <List.Content floated="right">
                                            <Icon
                                                name="delete"
                                                link
                                                color="grey"
                                                onClick={() => this.removeFromRecents(recent.id)}
                                                title="Remove"
                                            />
                                        </List.Content>
                                        <List.Content>
                                            <List.Header
                                                as="a"
                                                onClick={() => this.loadRecentQuery(recent)}
                                                style={{ fontSize: '0.9em' }}
                                            >
                                                {recent.name}
                                            </List.Header>
                                            {recent.description && (
                                                <List.Description style={{ fontSize: '0.8em', color: '#888' }}>
                                                    {recent.description}
                                                </List.Description>
                                            )}
                                        </List.Content>
                                    </List.Item>
                                ))}
                            </List>
                        )}
                    </Segment>
                </Grid.Column>
            </Grid>
        );
    }
}
