import * as React from 'react';
import { Spinner, Box, Text, Heading } from '@gluestack-ui/themed';
import { PermissionType } from 'common';
import { IPreDefinedPermissions } from '@adminide-stack/core';
import { get } from 'lodash-es';
import { usePermissionAutoFetch } from '@adminide-stack/platform-client';

export enum WithPermissionBehaviour {
    hide,
    showUnAuthorized,
    showAlternative,
}

export interface IWithPermissionProps {
    children?: React.ReactElement;
    permissionKeys: IPreDefinedPermissions[];
    permissionTypes?: PermissionType[];
    behaviour?: WithPermissionBehaviour;
    message?: string;
    alternative?: React.ReactElement;
    render?: React.FunctionComponent<{ hasPermission: boolean }>;
}

export const WithPermission = ({
    permissionKeys,
    children,
    permissionTypes = [PermissionType.Allow],
    behaviour = WithPermissionBehaviour.hide,
    message = "You don't have permission to access this resource, contact owner",
    alternative,
    render,
}: IWithPermissionProps) => {
    // const { data: permissions, loading: permissionLoading } = usePermissionAutoFetch();
    const { permissions, loading: permissionLoading } = usePermissionAutoFetch();
    const hasPermission = React.useMemo(() => {
        return permissionKeys.some((key) => permissionTypes.includes(get(permissions?.resolveConfiguration, key)));
    }, [permissions, permissionTypes, permissionKeys]);

    console.log('hasPermission', hasPermission);
    console.log('permissions', JSON.stringify(permissions));

    if (permissionLoading) {
        return <Spinner />;
    }

    if (typeof render === 'function') {
        return render({ hasPermission });
    }

    if (hasPermission) {
        return children;
    }

    if (behaviour === WithPermissionBehaviour.showAlternative) {
        return alternative;
    }
    if (behaviour === WithPermissionBehaviour.showUnAuthorized) {
        if (permissionLoading) {
            return <Spinner />;
        }
        return (
            <Box>
                <Heading>Missing Permission</Heading>
                <Text>{message}</Text>
            </Box>
        );
    }
    return null;
};

WithPermission.defaultProps = {
    permissionTypes: [PermissionType.Allow],
    behaviour: WithPermissionBehaviour.hide,
    message: "You don't have permission to access this resource, contact owner",
    disabledProps: {
        disabled: true,
    },
};

export const WithPermissionContainer = React.memo((props: IWithPermissionProps) => <WithPermission {...props} />);
export default WithPermissionContainer;
// export const WithPermissionContainer = (props: IWithPermissionProps) => <WithPermission {...props} />;
