import React from 'react';
import {CascadeSelectSingleInputComponent as Input} from '../../molecules/cascade-select-single-input';
import {
    ICascadeSelectSingleProps as Props,
    ICascadeSelectSingleOption as IOption,
    ICascadeCascadeSelectSingle,
} from './cascade-select-single.type';
import Cascader from 'rc-cascader';
import {FormContainerComponent as FormContainer} from '../../molecules';
import {GlobalStyles} from '@mui/material';
import {CascadeSelectSingleStyle as S} from './cascade-select-single.style';

export const CascadeSelectSingleComponent: React.FC<Props> = ({
    id,
    error,
    label,
    hint,
    containerClassName,
    mandatory,
    placeholder,
    value,
    onChange,
    ...cascaderProps
}) => {
    const onChangeCascade: ICascadeCascadeSelectSingle['onChange'] = (
        newValue,
        selectedOption,
    ) => {
        if (!onChange) return;
        onChange({
            label: selectedOption
                ?.map((option: IOption) => option?.label)
                ?.join(' / '),
            value: newValue?.[newValue?.length - 1],
        });
    };
    return (
        <>
            <GlobalStyles styles={S.customizations} />
            <FormContainer
                id={id}
                error={error}
                label={label}
                hint={hint}
                mandatory={mandatory}
                containerClassName={containerClassName}
            >
                <Cascader
                    showCheckedStrategy='SHOW_PARENT'
                    changeOnSelect
                    expandIcon={<S.ChevronRightIcon />}
                    direction='rtl'
                    loadingIcon={<S.Spinner />}
                    onChange={onChangeCascade}
                    checkable={false}
                    {...cascaderProps}
                >
                    <Input value={value?.label} placeholder={placeholder} />
                </Cascader>
            </FormContainer>
        </>
    );
};
