import type { Option } from '@/types';

/**
 * A ticket status as the pickers receive it: the label plus the block of the
 * lifecycle it belongs to.
 */
export type GroupedTicketStatus = Option & {
    color?: string;
    group?: string;
    group_label?: string;
};

/**
 * The ticket statuses, grouped into the blocks of the lifecycle.
 *
 * There are a dozen of them now that the warranty states are first class, and
 * a flat list of twelve makes the person moving a ticket read all of them to
 * find the one they mean. The groups are the same on every screen because they
 * come from the enum: on the desk, waiting on someone, warranty and
 * manufacturer, finished.
 */
export function TicketStatusOptions({
    statuses,
}: {
    statuses: GroupedTicketStatus[];
}) {
    const groups = new Map<
        string,
        { label: string; items: GroupedTicketStatus[] }
    >();

    for (const status of statuses) {
        const key = status.group ?? 'status';
        const group = groups.get(key) ?? {
            label: status.group_label ?? 'Statuses',
            items: [],
        };

        group.items.push(status);
        groups.set(key, group);
    }

    return (
        <>
            {[...groups.entries()].map(([key, group]) => (
                <optgroup key={key} label={group.label}>
                    {group.items.map((status) => (
                        <option key={status.value} value={status.value}>
                            {status.label}
                        </option>
                    ))}
                </optgroup>
            ))}
        </>
    );
}
