import { GridComponent } from '@/components/grid/GridComponent';
import type { AnsiTermColor, Grid, GridCell } from '@/types/grid';
import {
    type IZipper,
    ListZipper,
} from '@emprespresso/pengueno';
import { useCallback, useState } from 'react';

export interface ChooseArtProps {
    grid: Grid;
}

export const Paint: React.FC<ChooseArtProps> = ({ grid }) => {
    const [selectedColor, setSelectedColor] = useState<AnsiTermColor>({
        foreground: { r: 5, g: 5, b: 5 },
        background: null,
    });
    const [history, setHistory] = useState<IZipper<Grid>>(
        ListZipper.from([grid]),
    );

    const cellInteractionCallback = useCallback(
        (cell: GridCell) => {
            setHistory((currentHistory) => {
                const currentGrid = currentHistory.read().get();
                const newGrid = currentGrid.map((row) => [...row]); // Deep copy for current state
                newGrid[cell.y][cell.x] = { ...cell, color: selectedColor };
                return currentHistory.prepend(newGrid).previous().get();
            });
        },
        [selectedColor],
    );

    return (
        <div>
            <GridComponent
                grid={history.read().get()}
                onCellInteract={cellInteractionCallback}
            />
            <button
                disabled={
                    !history
                        .next()
                        .flatMap((it) => it.read())
                        .present()
                }
                onClick={() => setHistory((history) => history.next().get())}
            >
                Undo
            </button>
            <button
                disabled={
                    !history
                        .previous()
                        .flatMap((it) => it.read())
                        .present()
                }
                onClick={() =>
                    setHistory((history) => history.previous().get())
                }
            >
                Redo
            </button>
        </div>
    );
};
