import React from 'react';
import CustomRadioSelect, { CustomRadioSelectProps } from "./CustomRadioSelect";
import { CustomSelectOptions } from "../../../../models/ReactComponents";
import SelectItem from "./SelectItem";
import {oneOf} from "prop-types";

// CustomRadioSelect treats value === null/undefined/'' as "no selection",
// so an option whose real value is '' (e.g. "select all" from the backend)
// never gets highlighted. We remap it to a sentinel on the way in and
// translate it back to the real value on the way out.
const EMPTY_SENTINEL = '__empty__';
const isEmptyish = (v: any) => v === null || v === undefined || v === '';

interface MakeCustomRadioSelectProps extends Omit<CustomRadioSelectProps, 'children'> {
    selectAllOption?: string | null; // attaches option to options lookup
    selectAllOptionValue?: string | number | null; // attaches option to options lookup
    options: CustomSelectOptions;
}

const MakeCustomRadioSelect = ({
                                   options,
                                   selectAllOption,
                                   selectAllOptionValue = null,
                                   value,
                                   handleChange,
                                   ...props
                               }: MakeCustomRadioSelectProps) => {

    // clone options safely
    const ooptions = [...options];

    // only add the "select all" option if text is provided
    if (selectAllOption !== null && selectAllOption !== undefined && selectAllOption !== '') {
        ooptions.unshift({
            value: selectAllOptionValue, // can be null safely
            name: selectAllOption
        });
    }

    return (
        <CustomRadioSelect
            {...props}
            value={isEmptyish(value) ? EMPTY_SENTINEL : value}
            handleChange={(v) => {
                if (v === EMPTY_SENTINEL) {
                    const match = ooptions.find((o) => isEmptyish(o.value));
                    handleChange(match?.value != null ? String(match.value) : '');
                    return;
                }
                handleChange(v);
            }}
        >
            {ooptions.map((opt) => (
                <SelectItem
                    disabled={opt.is_disabled}
                    key={String(opt.value ?? 'null')} // ensure key uniqueness
                    value={isEmptyish(opt.value) ? EMPTY_SENTINEL : opt.value} // remap empty values so CustomRadioSelect can match/highlight them
                >
                    {opt.name}
                </SelectItem>
            ))}
        </CustomRadioSelect>
    );
};

export default MakeCustomRadioSelect;
