import { Children, cloneElement, isValidElement } from '@wordpress/element';
import clsx from '../../../utils/clsx';
import {
    gapStyle,
    marginStyle,
    marginTopStyle,
    paddingStyle,
    paddingTopStyle,
} from '../../../utils/styles';

const GridStack = ({
    id,
    style,
    className = '',
    margin,
    marginTop,
    padding,
    paddingTop,
    as,
    children,
    columns = 1,
    rows,
    min = '0',
    max = '1fr',
    gap = 16,
    rounded = 'none',
    align,
    blockAlign,
    templateAreas,
}) => {
    let gridTemplateColumns = '';

    if (columns === 'auto-fit' || columns === 'auto-fill') {
        gridTemplateColumns = `repeat(${columns}, minmax(${min}, ${max}))`;
    } else if (typeof columns === 'number') {
        gridTemplateColumns = `repeat(${columns}, minmax(${min}, ${max}))`;
    } else {
        gridTemplateColumns = columns;
    }

    const classes = ['grid'];

    const gapValue = gapStyle(gap);

    if (align) classes.push(`justify-${align}`);
    if (blockAlign) classes.push(`items-${blockAlign}`);
    if (rounded) classes.push(`rounded-${rounded}`);
    if (className) classes.push(className);

    const computedStyle = {
        gridTemplateColumns,
        ...(rows ? { gridTemplateRows: rows } : {}),
        ...(templateAreas && {
            gridTemplateAreas: templateAreas.map((r) => `"${r}"`).join(' '),
        }),
        ...gapValue,
        ...style,
        ...marginStyle(margin),
        ...marginTopStyle(marginTop),
        ...paddingStyle(padding),
        ...paddingTopStyle(paddingTop),
    };

    const enhancedChildren = Children.map(children, (child) => {
        if (!isValidElement(child)) return child;
        const el = child;
        const area = el.props.gridArea;

        return cloneElement(el, {
            style: {
                ...(el.props.style || {}),
                ...(area ? { gridArea: area } : {}),
            },
        });
    });

    const Tag = as || 'div';

    return (
        <Tag id={id} style={computedStyle} className={clsx(...classes)}>
            {enhancedChildren}
        </Tag>
    );
};

export default GridStack;
