import { __ } from '@wordpress/i18n';
import {
    CheckboxControl,
    Button,
    __experimentalVStack as VStack,
    __experimentalHStack as HStack,
    FlexItem,
} from '@wordpress/components';
import { chevronUp, chevronDown } from '@wordpress/icons';
import { useMemo } from '@wordpress/element';

export function ReorderableMultiSelect({
    options,          // [{ key, label }]
    selectedKeys,     // enabled list, order matters
    onChangeSelected, // fn(newSelected[])
}) {
    const allKeys = useMemo(() => options.map(o => o.key), [options]);
    const selectedSet = useMemo(() => new Set(selectedKeys), [selectedKeys]);

    const labelByKey = useMemo(() => {
        const m = {};
        options.forEach(o => { m[o.key] = o.label; });
        return m;
    }, [options]);

    // Selected first in saved order, then unselected in original options order
    const displayKeys = useMemo(() => {
        const selectedInAll = selectedKeys.filter(k => allKeys.includes(k));
        const unselected = allKeys.filter(k => !selectedSet.has(k));
        return [...selectedInAll, ...unselected];
    }, [allKeys, selectedKeys, selectedSet]);

    const toggle = (key) => {
        if (selectedSet.has(key)) {
            onChangeSelected(selectedKeys.filter(k => k !== key));
        } else {
            onChangeSelected([...selectedKeys, key]);
        }
    };

    const move = (key, dir) => {
        const i = selectedKeys.indexOf(key);
        if (i === -1) return; // only reorder selected items
        const j = dir === 'up' ? i - 1 : i + 1;
        if (j < 0 || j >= selectedKeys.length) return;
        const next = selectedKeys.slice();
        [next[i], next[j]] = [next[j], next[i]];
        onChangeSelected(next);
    };

    return (
        <VStack spacing={2}>
            {displayKeys.map((key) => {
                const checked = selectedSet.has(key);
                const idx = selectedKeys.indexOf(key);
                return (
                    <HStack key={key} alignment="left" justify="space-between">
                        <FlexItem>
                            <CheckboxControl
                                label={labelByKey[key] || key}
                                checked={checked}
                                onChange={() => toggle(key)}
                            />
                        </FlexItem>
                        <FlexItem>
                            <HStack spacing={1}>
                                <Button
                                    icon={chevronUp}
                                    label={__('Move up', 'lead-gen')}
                                    onClick={() => move(key, 'up')}
                                    size="small"
                                    variant="secondary"
                                    disabled={!checked || idx <= 0}
                                />
                                <Button
                                    icon={chevronDown}
                                    label={__('Move down', 'lead-gen')}
                                    onClick={() => move(key, 'down')}
                                    size="small"
                                    variant="secondary"
                                    disabled={!checked || idx === selectedKeys.length - 1}
                                />
                            </HStack>
                        </FlexItem>
                    </HStack>
                );
            })}
        </VStack>
    );
}
