import {
    IconLayoutAlignLeft, IconLayoutAlignCenter, IconLayoutAlignRight,
    IconLayoutAlignTop, IconLayoutAlignMiddle, IconLayoutAlignBottom,
} from '@tabler/icons-react';
import { PanelSection, Row, NumInput, IconBtn, T } from '../../ui/figma';
import { combinedBounds } from '../../utils/geometry';

/**
 * Position + size for a whole-group selection.
 * Moving translates every member; W/H scale the block uniformly
 * (geometry + font sizes), anchored at the group's top-left.
 */
export default function GroupSection({ members, canvas, updateElements }) {
    const bounds = combinedBounds(members);
    if (!bounds) return null;

    const moveBy = (dx, dy) => {
        if (!dx && !dy) return;
        const patches = {};
        members.forEach((m) => {
            patches[m.id] = { x: Math.round((m.x + dx) * 100) / 100, y: Math.round((m.y + dy) * 100) / 100 };
        });
        updateElements(patches);
    };

    const scaleTo = (s) => {
        if (!Number.isFinite(s) || s <= 0) return;
        const clamped = Math.min(40, Math.max(0.02, s));
        const patches = {};
        members.forEach((m) => {
            const patch = {
                x: Math.round((bounds.x + (m.x - bounds.x) * clamped) * 100) / 100,
                y: Math.round((bounds.y + (m.y - bounds.y) * clamped) * 100) / 100,
                width: Math.max(1, Math.round(m.width * clamped * 100) / 100),
                height: Math.max(1, Math.round(m.height * clamped * 100) / 100),
            };
            if (m.styles?.fontSize != null) {
                patch.styles = { fontSize: Math.max(2, Math.round(m.styles.fontSize * clamped * 10) / 10) };
            }
            patches[m.id] = patch;
        });
        updateElements(patches);
    };

    const alignBlock = (alignment) => {
        const { width: cw, height: ch } = canvas;
        let dx = 0;
        let dy = 0;
        if (alignment === 'left') dx = -bounds.x;
        if (alignment === 'center') dx = (cw - bounds.width) / 2 - bounds.x;
        if (alignment === 'right') dx = cw - bounds.width - bounds.x;
        if (alignment === 'top') dy = -bounds.y;
        if (alignment === 'middle') dy = (ch - bounds.height) / 2 - bounds.y;
        if (alignment === 'bottom') dy = ch - bounds.height - bounds.y;
        moveBy(dx, dy);
    };

    const alignBtn = (value, Icon, label) => (
        <IconBtn key={value} icon={Icon} label={label} onClick={() => alignBlock(value)} className="flex-1" />
    );

    return (
        <>
            <PanelSection title="Position">
                <div className={`flex items-center gap-0.5 mb-2 rounded-[5px] p-0.5 ${T.inputBg}`}>
                    {alignBtn('left', IconLayoutAlignLeft, 'Align left')}
                    {alignBtn('center', IconLayoutAlignCenter, 'Align horizontal centers')}
                    {alignBtn('right', IconLayoutAlignRight, 'Align right')}
                    <span className="w-px h-4 bg-black/10 dark:bg-white/10 mx-0.5" />
                    {alignBtn('top', IconLayoutAlignTop, 'Align top')}
                    {alignBtn('middle', IconLayoutAlignMiddle, 'Align vertical centers')}
                    {alignBtn('bottom', IconLayoutAlignBottom, 'Align bottom')}
                </div>
                <Row>
                    <NumInput
                        label="X"
                        value={Math.round(bounds.x)}
                        min={-8000}
                        max={8000}
                        onChange={(v) => moveBy(v - bounds.x, 0)}
                    />
                    <NumInput
                        label="Y"
                        value={Math.round(bounds.y)}
                        min={-8000}
                        max={8000}
                        onChange={(v) => moveBy(0, v - bounds.y)}
                    />
                </Row>
            </PanelSection>
            <PanelSection title="Layout">
                <Row>
                    <NumInput
                        label="W"
                        title="Group width (scales contents)"
                        value={Math.round(bounds.width)}
                        min={1}
                        max={16000}
                        onChange={(v) => scaleTo(v / bounds.width)}
                    />
                    <NumInput
                        label="H"
                        title="Group height (scales contents)"
                        value={Math.round(bounds.height)}
                        min={1}
                        max={16000}
                        onChange={(v) => scaleTo(v / bounds.height)}
                    />
                </Row>
                <p className={`mt-1 text-[10px] leading-snug ${T.textFaint}`}>
                    Resizing a group scales everything inside it. Double-click an
                    element on the canvas to edit it individually.
                </p>
            </PanelSection>
        </>
    );
}
