export class InventoryManager {
    constructor(scene) {
        this.scene = scene;
        this.isOpen = false;
        this.inventory = {};
        this.backpackIcon = null;
        this.inventoryUI = null;
        this.closeButton = null;
    }

    init() {
        const cam = this.scene.cameras.main;
        this.backpackIcon = this.scene.physics.add.image(cam.worldView.width-150, cam.worldView.height-150, 'backpack')
            .setOrigin(0.5)
            .setScale(.5)
            .setScrollFactor(0)
            .setDepth(99);
        
        // Create inventory UI (hidden initially)
        this.createInventoryUI();
        
        // Add click event to toggle inventory
        this.backpackIcon.setInteractive();
        this.backpackIcon.on('pointerdown', () => {
            this.toggleInventory();
        });
    }

    createInventoryUI() {
        const scene = this.scene;
        
        this.inventoryUI = scene.add.image(1130,570,'inventory').setOrigin(0.5).setScrollFactor(0).setDepth(150).setScale(0);
        
        // Create close button
        this.closeButton = scene.add.rectangle(
            705,
            85,
            30,
            30,
            0xFF4444
        ).setOrigin(0.5).setScrollFactor(0).setDepth(150);
        
        // Add X to close button
        this.closeButtonText = scene.add.text(
            668,
            85,
            'Close  X',
            { 
                fontSize: '24px', 
                fill: '#FFFFFF',
                fontFamily: 'eraserDust, Arial', 
            }
        ).setOrigin(0.5).setScrollFactor(0).setDepth(150);
        
        // Hide inventory UI initially
        this.inventoryUI.setVisible(false);
        this.closeButton.setVisible(false);
        this.closeButtonText.setVisible(false);
        
        // Add click event to close button
        this.closeButton.setInteractive();
        this.closeButton.on('pointerdown', () => {
            this.toggleInventory();
        });
    }

    toggleInventory() {
        this.isOpen = !this.isOpen;
        
        if (this.isOpen) {
            this.scene.player.stop();
            this.scene.player.canMove = false;
            // Show inventory UI and close button
            this.inventoryUI.setVisible(true);
            this.backpackIcon.setVisible(false);
            this.scene.tweens.add({
                targets: this.inventoryUI,
                scale: 1,
                angle: 360,
                duration: 400,
                x: 640,
                y: 360,
                onComplete: ()=> {
                    this.closeButton.setVisible(true);
                    this.closeButtonText.setVisible(true);
                    this.showInventory();
                }
            });
        } else {
            // Hide inventory UI and close button
            this.closeButton.setVisible(false);
            this.closeButtonText.setVisible(false);
            this.backpackIcon.setVisible(true);

            // Destroy all items in the inventory display group
            if (this.inventoryDisplay) {
                this.inventoryDisplay.clear(true, true); // Clear group and destroy children
            }

            this.scene.tweens.add({
                targets: this.inventoryUI,
                scale: 0,
                angle: 360,
                duration: 400,
                x: 1130,
                y: 570,
                onComplete: () => {
                    this.inventoryUI.setVisible(false);
                    this.scene.player.canMove = true;
                    this.inventoryDisplay = null;
                } 
            });
        }
    }

    showInventory() {
        // Add X to close button
        this.inventoryBG = this.scene.add.rectangle(
            225,
            195,
            820,
            200,
            0x000000,
            .6
        ).setOrigin(0).setScrollFactor(0).setDepth(155).setAlpha(0.6);

        this.inventoryCraftOne = this.scene.add.image(225,405, 'craftDrop').setOrigin(0).setScrollFactor(0).setDepth(156);
        this.inventoryCraftTwo = this.scene.add.image(450,405, 'craftDrop').setOrigin(0).setScrollFactor(0).setDepth(156);

        // Add circular button with plus symbol between craft slots
        this.craftButton = this.scene.add.circle(
            437, // Centered between the two craft slots (225 + 225)/2 = 225, but we want it at x=337.5 which is halfway between both slots
            475,
            40, // 100px diameter circle
            0x00FF00, // Green color for the button
            0.6 // Alpha .6
        ).setOrigin(0.5).setScrollFactor(0).setDepth(157);
        
        this.craftButtonText = this.scene.add.text(
            437,
            475,
            'Craft',
            { 
                fontSize: '28px', 
                fill: '#FFFFFF',
                fontFamily: 'eraserDust, Arial', 
            }
        ).setOrigin(0.5).setScrollFactor(0).setDepth(158);

        // Make the button interactive
        this.craftButton.setInteractive();
        this.craftButton.on('pointerdown', () => {
            console.log('Craft button clicked');
            // Add craft functionality here
        });

        // Display inventory items
        let yPosition = 215;
        let xStart = 245;
        let row = 0;

        this.inventoryDisplay = this.scene.physics.add.group();
        this.inventoryDisplay.add(this.inventoryBG);
        this.inventoryDisplay.add(this.craftButton);
        this.inventoryDisplay.add(this.craftButtonText);
        this.inventoryDisplay.add(this.inventoryCraftOne);
        this.inventoryDisplay.add(this.inventoryCraftTwo);
        
        for (const [itemType, itemData] of Object.entries(this.inventory)) {
            const { amount, sprite } = itemData;
            
            // Create sprite
            const itemSprite = this.scene.physics.add.sprite(xStart, yPosition, 'objects', sprite)
                .setOrigin(0.5)
                .setScale(0.5)
                .setScrollFactor(0)
                .setDepth(160);
            
            // Make the item draggable
            itemSprite.setInteractive();
            this.scene.input.setDraggable(itemSprite);
            
            // Add drag events
            itemSprite.on('dragstart', (pointer, dragX, dragY) => {
                // Bring to front when dragging
                itemSprite.setDepth(200);
                
                // Create a temporary visual clone for dragging
                this.dragClone = this.scene.add.sprite(dragX, dragY, 'objects', sprite)
                    .setOrigin(0.5)
                    .setScale(0.5)
                    .setScrollFactor(0)
                    .setDepth(210);
            });
            
            itemSprite.on('drag', (pointer, dragX, dragY) => {
                // Move the clone with the mouse
                if (this.dragClone) {
                    this.dragClone.setPosition(dragX, dragY);
                }
            });
            
            itemSprite.on('dragend', (pointer, dragX, dragY) => {
                // Remove the clone
                if (this.dragClone) {
                    this.dragClone.destroy();
                    this.dragClone = null;
                }
                
                // Reset item depth
                itemSprite.setDepth(160);
                
                // Check if dropped on a craft slot
                const craftOneBounds = this.inventoryCraftOne.getBounds();
                const craftTwoBounds = this.inventoryCraftTwo.getBounds();
                
                if (Phaser.Geom.Rectangle.ContainsPoint(craftOneBounds, pointer.position)) {
                    console.log(`Dropped ${itemType} onto Craft Slot 1`);
                    // Handle drop on craft slot 1
                } else if (Phaser.Geom.Rectangle.ContainsPoint(craftTwoBounds, pointer.position)) {
                    console.log(`Dropped ${itemType} onto Craft Slot 2`);
                    // Handle drop on craft slot 2
                }
            });
            
            // Create item name text
            const itemName = this.scene.add.text(
                xStart + 40,
                yPosition - 10,
                itemType.charAt(0).toUpperCase() + itemType.slice(1),
                { 
                    fontSize: '16px', 
                    fill: '#FFFFFF',
                    fontFamily: 'eraserDust, Arial', 
                }
            ).setOrigin(0).setScrollFactor(0).setDepth(160);
            
            // Create quantity text
            const itemQuantity = this.scene.add.text(
                xStart + 40,
                yPosition + 15,
                `x${amount}`,
                { 
                    fontSize: '14px', 
                    fill: '#FFFF00',
                    fontFamily: 'eraserDust, Arial', 
                }
            ).setOrigin(0).setScrollFactor(0).setDepth(160);

            this.inventoryDisplay.add(itemSprite);
            this.inventoryDisplay.add(itemName);
            this.inventoryDisplay.add(itemQuantity);
            
            // Move to next row
            yPosition += 50;
            row ++;
            if (row === 3) {
                row = 0;
                yPosition = 215;
                xStart += 200;
            }
        }

        // Make craft slots interactive for drop targets
        this.inventoryCraftOne.setInteractive();
        this.inventoryCraftTwo.setInteractive();
    }

    addItem(item) {
        const type = item.props.type;
        const amount = item.props.amount;
        const sprite = item.props.sprite;
        if (type in this.inventory) {
            this.inventory[type].amount += amount;
        } else {
            this.inventory[type] = {
                amount: amount,
                sprite: sprite
            }
        }
        this.scene.tweens.add({
            targets: this.backpackIcon,
            angle: 360,
            delay: 500,
            duration: 500
        });
        this.scene.tweens.add({
            targets: this.backpackIcon,
            scale: 0.8,
            delay: 500,
            yoyo: true,
            ease: 'Bounce',
            duration: 500
        });
    }

    removeItem(item) {
        const index = this.inventory.indexOf(item);
        if (index > -1) {
            this.inventory.splice(index, 1);
        }
    }

    update(delta) {
        // Inventory update logic can go here
    }
}