import * as React from 'react';
import { ReactElement } from 'react';
import { Spinner } from '@gluestack-ui/themed';
import { logger } from '@cdm-logger/client';
import { useSetting } from '@adminide-stack/platform-client';
import { IConfiguration, IConfigurationsFlattenedKeys } from 'common';

interface IProps {
    policyKey: IConfigurationsFlattenedKeys;
    Child: React.FC<{ value: unknown }>;
    childProps?: Record<string, any>;
    showLoading?: boolean;
    skeletonProps?: Record<string, unknown>;
}

export const WithPolicy = (props: IProps): ReactElement => {
    const { policyKey, showLoading, Child, skeletonProps = {}, childProps = {} } = props;
    const {
        data: policy,
        loading,
        error,
    } = useSetting({
        configKey: policyKey,
    });
    if (error) {
        logger.error(error, `WithPolicy.name`);
    }
    if (showLoading && loading) {
        return <Spinner color={'#ff5a00'} />;
    }

    return <Child {...childProps} value={policy} />;
};
