'use client';

import { useCallback, useContext, useEffect } from 'react';

import { barcodeToProduct, generateRandomBarcode } from '../../lib/barcode';
import { ProductInfo } from './components/ProductInfo/ProductInfo';
import { Bins } from './components/Bins/Bins';
import { DefectPanel } from './components/DefectPanel/DefectPanel';
import { BinnerContext } from './context/BinnerContext';

import styles from './page.module.scss';

export default function Page() {
    const { bin, item, setBin, setItem } = useContext(BinnerContext);

    const handleKeydown = useCallback((event: KeyboardEvent) => {
        switch (event.key) {
            case ' ':
                event.preventDefault();
                const barcode = generateRandomBarcode();
                setItem(barcodeToProduct(barcode));
                break;
            case 'Escape':
                event.preventDefault();
                if (bin !== null) {
                    setBin(null);
                } else {
                    setItem(null);
                }
                break;
        }
    }, [bin, setBin, setItem]);

    useEffect(() => {
        window.addEventListener('keydown', handleKeydown);
        return () => {
            window.removeEventListener('keydown', handleKeydown);
        };
    }, [handleKeydown]);

    return (
        <main className={styles.page}>
            <div className={styles.banner}>Use the spacebar to simulate a barcode read</div>
            <ProductInfo />
            <div className={styles.interactionPanel}>
                {bin !== null 
                    ? <DefectPanel />
                    : <Bins />
                }
            </div>
        </main>
    );
}