import React, { render } from 'preact';
import cn from 'clsx';
import { TileType } from './world';

import "@common/assets/vga.font.css"
import styles from './assets/ui.module.css';
import conveyorImage from './assets/img/conveyor.png';
import extractorImage from './assets/img/extractor.png';
import notImage from './assets/img/not.png';
import andImage from './assets/img/and.png';
import orImage from './assets/img/or.png';
import { range } from '@common/utils';

export enum ToolType {
    SELECT,
    EXTRACTOR,
    CONVEYOR,
    NOT,
    OR,
    AND,
}

interface Tool {
    type: ToolType;
    title: string;
    icon: string;
    tileType?: TileType;
}

const TOOLS: (Tool | null)[] = [
    {
        type: ToolType.EXTRACTOR,
        title: 'Extractor',
        icon: extractorImage.src,
        tileType: TileType.EXTRACTOR,
    },
    {
        type: ToolType.CONVEYOR,
        title: 'Conveyor',
        icon: conveyorImage.src,
        tileType: TileType.CONVEYOR,
    },
    {
        type: ToolType.NOT,
        title: 'Logical NOT',
        icon: notImage.src,
        tileType: TileType.NOT,
    },
    {
        type: ToolType.AND,
        title: 'Logical AND',
        icon: andImage.src,
        tileType: TileType.AND,
    },
    {
        type: ToolType.OR,
        title: 'Logical OR',
        icon: orImage.src,
        tileType: TileType.OR,
    },
    null, // 6
    null, // 7
    null, // 8
    null, // 9
];

export default class UI {
    private root: HTMLElement;
    private currentTool: Tool = TOOLS[0]!;

    constructor() {
        this.root = document.createElement('div');
        this.root.className = styles.controls;
        document.body.appendChild(this.root);

        this.render();
    }

    render() {
        const fragment = <>
            {range(9).map(i => (
                <Button
                    keyBinding={i + 1}
                    tool={TOOLS[i]}
                    onClick={() => this.onToolSelect(TOOLS[i])}
                    active={this.currentTool.type === TOOLS[i]?.type}
                />
            ))}
        </>;
        render(fragment, this.root);
    }

    onToolSelect(tool: Tool | null) {
        if (tool) {
            this.currentTool = tool;
            this.render();
        }
    }

    useSlot(slot: number) {
        this.onToolSelect(TOOLS[slot - 1]);
    }

    get selectedTool() {
        return this.currentTool;
    }
}

interface ButtonProps {
    keyBinding: number;
    active: boolean;
    tool: Tool | null;
    onClick?: () => void;
}
function Button({ keyBinding, active, tool, onClick }: ButtonProps) {
    return (
        <div class={cn([styles.button, active && styles.active, !tool && styles.disabled])} onClick={() => onClick?.()}>
            <img src={tool?.icon} class={styles.icon} />
            <div class={styles.keyBinding}>{keyBinding}</div>
        </div>
    );
}