'use client';

import { useEffect, useState } from 'react';

import { BinsContents, getBinsContents, switchBin } from '@/app/lib/data/binned';
import { Binned, BinnedDocument } from '@/models/binned';
import { binToLabel } from '@/app/lib/bin.enum';

import styles from './page.module.scss';
import Link from 'next/link';

export default function Page() {
    const [bins, setBins] = useState<BinsContents>();
    const [dragging, setDragging] = useState<Binned>();

    useEffect(() => {
        async function fetchData() {
            const bins = await getBinsContents();
            setBins(bins);
        }
        fetchData();
    }, []);

    const handleDrop = async (event: React.DragEvent) => {
        event.preventDefault();
        if (!dragging || !event.currentTarget.id) return;
        alert(`If this were functionally complete, the item would be moved from ${binToLabel(dragging.bin)} to ${binToLabel(parseInt(event.currentTarget.id))}`);
        await switchBin(parseInt(event.currentTarget.id), (dragging as BinnedDocument)._id);
        setDragging(undefined);
    };

    if (!bins) return null;

    return (
        <div className={styles.page}>
            <header className={styles.header}>
                <h1>Bin Contents</h1>
                <Link href="/dashboard"><button>&lt; Dashboard</button></Link> 
            </header>
            <div className={styles.bins}>
                {Object.entries(bins).map(([k, v]) => (
                    <div 
                        key={k}
                        id={k}
                        className={styles.bin}
                        onDragEnter={(event) => event.preventDefault()}
                        onDragOver={(event) => event.preventDefault()}
                        onDrop={handleDrop}
                    >
                        <h2>{binToLabel(parseInt(k))}</h2>
                        <ul onDrop={handleDrop}>
                            {v.length > 0 && v.map((item) => (<li key={(item as BinnedDocument)._id} onDragStart={() => setDragging(item)} draggable>{`${item.product} - ${item.weight}lbs`}</li>))}
                        </ul>
                    </div>
                ))}
            </div>
        </div>
    );
}