import React from 'react';
import superagent from 'superagent';
import {
    Header, Segment, Form, Button, Icon, Dropdown, Checkbox,
    Message, Step, Table, Label, Divider, Grid
} from 'semantic-ui-react';
import ExperimentalWrapper from './ExperimentalWrapper.jsx';

// Product type options for test orders
const PRODUCT_TYPE_OPTIONS = [
    { key: 'Beyond2', text: 'Beyond 2', value: 'Beyond2' },
    { key: 'Beyond2Eye', text: 'Beyond 2 Eye Tracking', value: 'Beyond2Eye' },
    { key: 'CustomCushion', text: 'Custom Cushion', value: 'CustomCushion' },
    { key: 'PrescriptionLenses', text: 'Prescription Lenses', value: 'PrescriptionLenses' },
    { key: 'AudioStrapV1', text: 'Audio Strap', value: 'AudioStrapV1' },
    { key: 'BeyondCushionV1', text: 'Standard Cushion', value: 'BeyondCushionV1' },
    { key: 'BeyondFibreOpticCableV1', text: 'Fibre Optic Cable', value: 'BeyondFibreOpticCableV1' },
];

const COUNTRY_OPTIONS = [
    { key: 'US', text: 'United States', value: 'US' },
    { key: 'CA', text: 'Canada', value: 'CA' },
    { key: 'GB', text: 'United Kingdom', value: 'GB' },
    { key: 'DE', text: 'Germany', value: 'DE' },
    { key: 'FR', text: 'France', value: 'FR' },
    { key: 'AU', text: 'Australia', value: 'AU' },
    { key: 'JP', text: 'Japan', value: 'JP' },
];

const TEST_STEPS = [
    { key: 'create_order', title: 'Create Test Order', description: 'Create order with TestData origin' },
    { key: 'verify_order', title: 'Verify Order Created', description: 'Check order state and properties' },
    { key: 'send_scan_request', title: 'Send Scan Request', description: 'Trigger scan request if applicable' },
    { key: 'simulate_scan', title: 'Simulate Scan Completion', description: 'Mark scan as ready' },
    { key: 'check_inventory', title: 'Check Inventory', description: 'Verify inventory availability' },
    { key: 'create_shipment', title: 'Create Shipment', description: 'Create shipment record' },
    { key: 'pick_inventory', title: 'Pick Inventory Items', description: 'Auto-pick inventory for shipment' },
    { key: 'generate_label', title: 'Generate Shipping Label', description: 'Create shipping label (test mode)' },
    { key: 'verify_final', title: 'Verify Final State', description: 'Check order and shipment status' },
];

export default class FactoryQATools extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            // Test configuration
            productType: 'Beyond2',
            customerEmail: `test-qa-${Date.now()}@bigscreenvr.com`,
            ipdValue: 63,
            priority: 50,
            country: 'US',

            // Test options
            createScanRequest: true,
            simulateManufacturing: true,
            autoPickInventory: true,
            generateLabel: false,
            completeShopifyFulfillment: false,

            // Test state
            isRunning: false,
            currentStep: null,
            stepResults: {},
            testOrderId: null,
            testShipmentId: null,
            error: null,
            logs: []
        };
    }

    addLog(message, type = 'info') {
        const timestamp = new Date().toLocaleTimeString();
        this.setState(prevState => ({
            logs: [...prevState.logs, { timestamp, message, type }]
        }));
    }

    async runStep(stepKey, stepFn) {
        this.setState({ currentStep: stepKey });
        this.addLog(`Starting: ${stepKey}`, 'info');

        try {
            const result = await stepFn();
            this.setState(prevState => ({
                stepResults: {
                    ...prevState.stepResults,
                    [stepKey]: { status: 'success', result }
                }
            }));
            this.addLog(`Completed: ${stepKey}`, 'success');
            return result;
        } catch (error) {
            this.setState(prevState => ({
                stepResults: {
                    ...prevState.stepResults,
                    [stepKey]: { status: 'error', error: error.message }
                },
                error: error.message
            }));
            this.addLog(`Failed: ${stepKey} - ${error.message}`, 'error');
            throw error;
        }
    }

    async createTestOrder() {
        const { productType, customerEmail, ipdValue, priority, country } = this.state;

        const res = await superagent
            .post('/api/admin/shop/test_order')
            .send({
                productType,
                customerEmail,
                ipdValue,
                priority,
                shippingCountryCode: country
            });

        const order = res.body;
        this.setState({ testOrderId: order.id });
        return order;
    }

    async verifyOrderCreated() {
        const { testOrderId } = this.state;
        const res = await superagent.get(`/api/admin/shop/order/${testOrderId}`);
        const order = res.body;

        if (order.origin !== 'TestData') {
            throw new Error(`Expected origin 'TestData', got '${order.origin}'`);
        }

        return order;
    }

    async sendScanRequest() {
        const { testOrderId, createScanRequest } = this.state;

        if (!createScanRequest) {
            return { skipped: true, reason: 'Scan request disabled in options' };
        }

        const res = await superagent
            .put(`/api/admin/shop/order/${testOrderId}`)
            .send({ action: 'SendScanRequest' });

        return res.body;
    }

    async simulateScanCompletion() {
        const { testOrderId, createScanRequest, simulateManufacturing } = this.state;

        if (!createScanRequest || !simulateManufacturing) {
            return { skipped: true, reason: 'Scan simulation disabled in options' };
        }

        // Get the scan request for this order
        const orderRes = await superagent.get(`/api/admin/shop/order/${testOrderId}`);
        const order = orderRes.body;

        if (!order.scanRequestId) {
            return { skipped: true, reason: 'No scan request found' };
        }

        // Mark scan as ready for fabricator
        const res = await superagent
            .put(`/api/admin/fabricator/scan_request/${order.scanRequestId}`)
            .send({ action: 'MarkReadyForFabricator' });

        return res.body;
    }

    async checkInventory() {
        const { testOrderId } = this.state;

        const res = await superagent.get(`/api/admin/shop/order/${testOrderId}`);
        const order = res.body;

        return {
            orderStatus: order.status,
            hasLineItems: order.lineItems && order.lineItems.length > 0,
            lineItemCount: order.lineItems ? order.lineItems.length : 0
        };
    }

    async createShipment() {
        const { testOrderId } = this.state;

        const res = await superagent
            .post('/api/admin/shipper/shipment')
            .send({ bigOrderId: testOrderId });

        const shipment = res.body;
        this.setState({ testShipmentId: shipment.uniqueId });
        return shipment;
    }

    async pickInventoryItems() {
        const { testShipmentId, autoPickInventory } = this.state;

        if (!autoPickInventory) {
            return { skipped: true, reason: 'Auto-pick disabled in options' };
        }

        const res = await superagent
            .put(`/api/admin/shipper/shipment/${testShipmentId}`)
            .send({ action: 'PickInventoryItem' });

        return res.body;
    }

    async generateShippingLabel() {
        const { testShipmentId, generateLabel } = this.state;

        if (!generateLabel) {
            return { skipped: true, reason: 'Label generation disabled in options' };
        }

        const res = await superagent
            .put(`/api/admin/shipper/shipment/${testShipmentId}`)
            .send({ action: 'GenerateShippingLabel' });

        return res.body;
    }

    async verifyFinalState() {
        const { testOrderId, testShipmentId } = this.state;

        const orderRes = await superagent.get(`/api/admin/shop/order/${testOrderId}`);
        const order = orderRes.body;

        let shipment = null;
        if (testShipmentId) {
            const shipmentRes = await superagent.get(`/api/admin/shipper/shipment/${testShipmentId}`);
            shipment = shipmentRes.body;
        }

        return {
            order: {
                id: order.id,
                status: order.status,
                origin: order.origin
            },
            shipment: shipment ? {
                id: shipment.uniqueId,
                status: shipment.status,
                trackingNumber: shipment.trackingNumber
            } : null
        };
    }

    async runFullTest() {
        this.setState({
            isRunning: true,
            currentStep: null,
            stepResults: {},
            testOrderId: null,
            testShipmentId: null,
            error: null,
            logs: []
        });

        try {
            await this.runStep('create_order', () => this.createTestOrder());
            await this.runStep('verify_order', () => this.verifyOrderCreated());
            await this.runStep('send_scan_request', () => this.sendScanRequest());
            await this.runStep('simulate_scan', () => this.simulateScanCompletion());
            await this.runStep('check_inventory', () => this.checkInventory());
            await this.runStep('create_shipment', () => this.createShipment());
            await this.runStep('pick_inventory', () => this.pickInventoryItems());
            await this.runStep('generate_label', () => this.generateShippingLabel());
            await this.runStep('verify_final', () => this.verifyFinalState());

            this.addLog('Test completed successfully!', 'success');
        } catch (error) {
            this.addLog(`Test failed: ${error.message}`, 'error');
        } finally {
            this.setState({ isRunning: false, currentStep: null });
        }
    }

    getStepStatus(stepKey) {
        const { currentStep, stepResults } = this.state;

        if (stepResults[stepKey]) {
            return stepResults[stepKey].status;
        }
        if (currentStep === stepKey) {
            return 'active';
        }
        return 'pending';
    }

    getStepIcon(status) {
        switch (status) {
            case 'success': return 'check circle';
            case 'error': return 'times circle';
            case 'active': return 'spinner';
            default: return 'circle outline';
        }
    }

    getStepColor(status) {
        switch (status) {
            case 'success': return 'green';
            case 'error': return 'red';
            case 'active': return 'blue';
            default: return 'grey';
        }
    }

    render() {
        const {
            productType, customerEmail, ipdValue, priority, country,
            createScanRequest, simulateManufacturing, autoPickInventory,
            generateLabel, completeShopifyFulfillment,
            isRunning, testOrderId, testShipmentId, error, logs, stepResults
        } = this.state;

        return (
            <ExperimentalWrapper title="Factory QA Tools">
                <Segment>
                    <Header as="h2">
                        <Icon name="cogs" />
                        <Header.Content>
                            Factory QA Tools
                            <Header.Subheader>
                                Run end-to-end tests of the order workflow with test-flagged data
                            </Header.Subheader>
                        </Header.Content>
                    </Header>
                </Segment>

                <Grid>
                    <Grid.Row>
                        <Grid.Column width={10}>
                            {/* Test Configuration */}
                            <Segment>
                                <Header as="h3">
                                    <Icon name="settings" />
                                    Test Configuration
                                </Header>

                                <Form>
                                    <Form.Group widths="equal">
                                        <Form.Field>
                                            <label>Product Type</label>
                                            <Dropdown
                                                selection
                                                options={PRODUCT_TYPE_OPTIONS}
                                                value={productType}
                                                onChange={(e, { value }) => this.setState({ productType: value })}
                                                disabled={isRunning}
                                            />
                                        </Form.Field>
                                        <Form.Field>
                                            <label>Country</label>
                                            <Dropdown
                                                selection
                                                options={COUNTRY_OPTIONS}
                                                value={country}
                                                onChange={(e, { value }) => this.setState({ country: value })}
                                                disabled={isRunning}
                                            />
                                        </Form.Field>
                                    </Form.Group>

                                    <Form.Group widths="equal">
                                        <Form.Input
                                            label="Customer Email"
                                            value={customerEmail}
                                            onChange={(e) => this.setState({ customerEmail: e.target.value })}
                                            disabled={isRunning}
                                        />
                                        <Form.Input
                                            label="IPD Value (mm)"
                                            type="number"
                                            value={ipdValue}
                                            onChange={(e) => this.setState({ ipdValue: parseInt(e.target.value) || 63 })}
                                            disabled={isRunning}
                                        />
                                        <Form.Input
                                            label="Priority (0-100)"
                                            type="number"
                                            value={priority}
                                            onChange={(e) => this.setState({ priority: parseInt(e.target.value) || 50 })}
                                            disabled={isRunning}
                                        />
                                    </Form.Group>

                                    <Divider />

                                    <Header as="h4">Test Options</Header>
                                    <Form.Group>
                                        <Form.Field>
                                            <Checkbox
                                                label="Create scan request (for cushion orders)"
                                                checked={createScanRequest}
                                                onChange={(e, { checked }) => this.setState({ createScanRequest: checked })}
                                                disabled={isRunning}
                                            />
                                        </Form.Field>
                                    </Form.Group>
                                    <Form.Group>
                                        <Form.Field>
                                            <Checkbox
                                                label="Simulate manufacturing completion"
                                                checked={simulateManufacturing}
                                                onChange={(e, { checked }) => this.setState({ simulateManufacturing: checked })}
                                                disabled={isRunning}
                                            />
                                        </Form.Field>
                                    </Form.Group>
                                    <Form.Group>
                                        <Form.Field>
                                            <Checkbox
                                                label="Auto-pick inventory items"
                                                checked={autoPickInventory}
                                                onChange={(e, { checked }) => this.setState({ autoPickInventory: checked })}
                                                disabled={isRunning}
                                            />
                                        </Form.Field>
                                    </Form.Group>
                                    <Form.Group>
                                        <Form.Field>
                                            <Checkbox
                                                label="Generate shipping label (test mode)"
                                                checked={generateLabel}
                                                onChange={(e, { checked }) => this.setState({ generateLabel: checked })}
                                                disabled={isRunning}
                                            />
                                        </Form.Field>
                                    </Form.Group>
                                    <Form.Group>
                                        <Form.Field>
                                            <Checkbox
                                                label="Complete Shopify fulfillment (careful!)"
                                                checked={completeShopifyFulfillment}
                                                onChange={(e, { checked }) => this.setState({ completeShopifyFulfillment: checked })}
                                                disabled={isRunning}
                                            />
                                        </Form.Field>
                                    </Form.Group>

                                    <Divider />

                                    <Button
                                        primary
                                        size="large"
                                        onClick={() => this.runFullTest()}
                                        loading={isRunning}
                                        disabled={isRunning}
                                    >
                                        <Icon name="play" />
                                        Start Full Test
                                    </Button>
                                </Form>
                            </Segment>

                            {/* Test Results */}
                            {(testOrderId || error) && (
                                <Segment>
                                    <Header as="h3">
                                        <Icon name="clipboard check" />
                                        Test Results
                                    </Header>

                                    {error && (
                                        <Message negative>
                                            <Message.Header>Test Failed</Message.Header>
                                            <p>{error}</p>
                                        </Message>
                                    )}

                                    {testOrderId && (
                                        <Message positive>
                                            <Message.Header>Test Order Created</Message.Header>
                                            <p>
                                                Order ID: <a href={`/shop/order/${testOrderId}`} target="_blank" rel="noopener noreferrer">{testOrderId}</a>
                                            </p>
                                            {testShipmentId && (
                                                <p>
                                                    Shipment ID: <a href={`/shipper/shipment/${testShipmentId}`} target="_blank" rel="noopener noreferrer">{testShipmentId}</a>
                                                </p>
                                            )}
                                        </Message>
                                    )}

                                    {Object.keys(stepResults).length > 0 && (
                                        <Table compact>
                                            <Table.Header>
                                                <Table.Row>
                                                    <Table.HeaderCell>Step</Table.HeaderCell>
                                                    <Table.HeaderCell>Status</Table.HeaderCell>
                                                    <Table.HeaderCell>Result</Table.HeaderCell>
                                                </Table.Row>
                                            </Table.Header>
                                            <Table.Body>
                                                {TEST_STEPS.map(step => {
                                                    const result = stepResults[step.key];
                                                    if (!result) return null;
                                                    return (
                                                        <Table.Row key={step.key} positive={result.status === 'success'} negative={result.status === 'error'}>
                                                            <Table.Cell>{step.title}</Table.Cell>
                                                            <Table.Cell>
                                                                <Label color={result.status === 'success' ? 'green' : 'red'}>
                                                                    {result.status}
                                                                </Label>
                                                            </Table.Cell>
                                                            <Table.Cell>
                                                                {result.error || (result.result?.skipped ? result.result.reason : 'OK')}
                                                            </Table.Cell>
                                                        </Table.Row>
                                                    );
                                                })}
                                            </Table.Body>
                                        </Table>
                                    )}
                                </Segment>
                            )}
                        </Grid.Column>

                        <Grid.Column width={6}>
                            {/* Test Steps Progress */}
                            <Segment>
                                <Header as="h3">
                                    <Icon name="tasks" />
                                    Test Steps
                                </Header>

                                <Step.Group vertical fluid size="small">
                                    {TEST_STEPS.map(step => {
                                        const status = this.getStepStatus(step.key);
                                        return (
                                            <Step key={step.key} active={status === 'active'} completed={status === 'success'} disabled={status === 'pending'}>
                                                <Icon name={this.getStepIcon(status)} color={this.getStepColor(status)} loading={status === 'active'} />
                                                <Step.Content>
                                                    <Step.Title>{step.title}</Step.Title>
                                                    <Step.Description>{step.description}</Step.Description>
                                                </Step.Content>
                                            </Step>
                                        );
                                    })}
                                </Step.Group>
                            </Segment>

                            {/* Logs */}
                            {logs.length > 0 && (
                                <Segment>
                                    <Header as="h3">
                                        <Icon name="list" />
                                        Logs
                                    </Header>
                                    <div style={{ maxHeight: '300px', overflowY: 'auto', fontFamily: 'monospace', fontSize: '12px' }}>
                                        {logs.map((log, index) => (
                                            <div key={index} style={{ color: log.type === 'error' ? 'red' : log.type === 'success' ? 'green' : 'inherit' }}>
                                                [{log.timestamp}] {log.message}
                                            </div>
                                        ))}
                                    </div>
                                </Segment>
                            )}
                        </Grid.Column>
                    </Grid.Row>
                </Grid>
            </ExperimentalWrapper>
        );
    }
}
