import React, { useCallback } from 'react';

import _ from 'lodash';
import {
    ArchiveIcon,
    CopyIcon,
    EyeIcon,
    EyeOffIcon,
    MoreHorizontalIcon,
    PencilIcon,
    SaveIcon,
    Trash2Icon,
    XIcon,
} from 'lucide-react';
import { useHotkeys } from 'react-hotkeys-hook';

import { rpcCache } from '@/api/cache';
import { rpc } from '@/api/request';
import {
    AdminActionMenuItemType,
    AllItemGIKTType,
    CollectionAccessType,
    CollectionMenuAMType,
    CollectionRelationType,
    ShmSocialType,
    StructureType,
} from '@/api/types';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuGroup,
    DropdownMenuItem,
    DropdownMenuSeparator,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
    MobileFab,
    MobileLink,
    MobileNavbar,
    MobilePage,
    MobilePopup,
} from '@/components/ui/mobile';
import { SystemWindowDialog } from '@/components/ui/system-window-dialog';
import { toast } from '@/componentsRoot/ToastRoot';
import { Lang } from '@/lang/Lang';
import { LL } from '@/lang/LL';
import useAppConfigStore, { useAppConfig } from '@/stores/appConfig';
import type { CollectionViewProps } from '@/types/dialog';
import { copyTextToClipboard } from '@/utils/helpers';

import { actionDialogRef } from '../../componentsRoot/ActionDialog';
import { confirmAlertRef } from '../../componentsRoot/ConfirmAlert';
import { socialInfoDialogRef } from '../../componentsRoot/SocialInfoDialog';
import AnyDropdownMenu from '../AnyDropdownMenu';
import CollectionFields from '../CollectionFields/CollectionFields';
import {
    ColCSS,
    RowCSS,
} from '../CollectionFields/components/GridCss';
import CollectionTable from '../CollectionTable/CollectionTable';
import MenuItem from '../MenuItem';
import { ServerIcon } from '../ServerIcon';
import { Button } from '../ui/button';
import { ButtonGroup } from '../ui/button-group';
import {
    Grid,
    GridCol,
    GridRow,
} from '../ui/grid';
import { Kbd } from '../ui/kbd';
import { Label } from '../ui/label';
import { Skeleton } from '../ui/skeleton';
import { requiredValidation } from './utils';

export type { CollectionViewProps };

const CollectionView = ({ collection, _id, modalKey, clonedFrom }: CollectionViewProps) => {

    const { closeDialog, focusDialogKey, openDialog, setHideTips, hideTips } = useAppConfig();

    const [structure, setStructure] = React.useState<StructureType | null>(null);
    const [collectionAccess, setCollectionAccess] = React.useState<CollectionAccessType | null>(null);


    const onHotkey = (index: number) => {

        if (focusDialogKey === modalKey) {

            if (collectionMenu?.allItems?.[index]) {
                onSelectMenu(collectionMenu?.allItems?.[index]?.key ?? '');
            }
        }


    }

    useHotkeys('shift+1', () => {
        onHotkey(0);
    });

    useHotkeys('shift+2', () => {
        onHotkey(1);
    });

    useHotkeys('shift+3', () => {
        onHotkey(2);
    });


    useHotkeys('shift+4', () => {
        onHotkey(3);
    });

    useHotkeys('shift+5', () => {
        onHotkey(4);
    });


    useHotkeys('shift+6', () => {
        onHotkey(5);
    });

    useHotkeys('shift+7', () => {
        onHotkey(6);
    });

    useHotkeys('shift+8', () => {
        onHotkey(7);
    });

    useHotkeys('shift+9', () => {
        onHotkey(8);
    });

    useHotkeys('shift+0', () => {
        onHotkey(9);
    });

    const hotkeyClose = () => {
        if (focusDialogKey === modalKey) {
            closeDialog(modalKey);
        }
    }

    useHotkeys('shift+x', () => {
        hotkeyClose();
    });

    const hotkeySave = () => {
        if (focusDialogKey === modalKey && !loading && collectionAccess?.buttons?.showSaveButton) {
            onSave('save');
        }
    }

    useHotkeys('shift+s', () => {
        hotkeySave();
    });

    const [collectionMenu, setCollectionMenu] = React.useState<CollectionMenuAMType | null>(null);

    const [selectMenu, setSelectMenu] = React.useState<{
        menu: AllItemGIKTType | null,
        relation: CollectionRelationType | null,
    } | null>(null);



    const [relations, setRelations] = React.useState<CollectionRelationType[] | null>(null);

    const [socials, setSocials] = React.useState<ShmSocialType[] | null>(null);

    const onSelectMenu = (key: string) => {

        let find = collectionMenu?.allItems?.find((item) => item.key === key);

        if (find?.group) {
            setSelectMenu({
                menu: find,
                relation: null,
            });
        }


    }



    const [loading, setLoading] = React.useState(true);

    const valuesRef = React.useRef<any>({});

    const loadActions = () => {
        if (!_id) {
            setActions([]);
            return;
        }

        rpc.allActions({ collection: collection, _ids: [_id] }).then((data) => {
            setActions(data?.result ?? []);
        });
    };


    const loadData = () => {
        setLoading(true);

        if (_id) {
            rpc.data({ collection: collection, _id: _id }).then((data) => {
                loadActions();
                valuesRef.current = data?.result?.data?.[0] ?? {};
            }).catch(() => {
                closeDialog(modalKey);
            }).finally(() => {
                setLoading(false);
            });

            rpc.collectionAccess({ collection: collection, ids: [_id] }).then((data) => {
                setCollectionAccess(data?.result ?? null);
            }).catch(() => {
                setCollectionAccess(null);
            });

            rpc.dataSocials({ collection: collection, _id: _id }).then((data) => {
                setSocials(data?.result ?? null);
            }).catch(() => {
                setSocials(null);
            });
        } else {
            rpc.emptyData({ collection: collection, clone: clonedFrom }).then((data) => {
                valuesRef.current = data.result ?? {};
            }).catch(() => {
                closeDialog(modalKey);
            }).finally(() => {
                setLoading(false);
            });
            rpc.collectionAccess({ collection: collection }).then((data) => {
                setCollectionAccess(data?.result ?? null);
            }).catch(() => {
                setCollectionAccess(null);
            });
        }
    };

    const [relationsLoading, setRelationsLoading] = React.useState<boolean>(false);
    const loadRelations = () => {
        if (_id) {
            setRelationsLoading(true);
            rpc.collectionRelations({ collection: collection, ids: [_id] }).then((data) => {
                setRelations(data?.result ?? null);
            }).finally(() => {
                setRelationsLoading(false);
            });
        } else {
            setRelations([]);
        }
    };

    React.useEffect(() => {
        setLoading(true);

        const dataPromise = _id
            ? rpc.data({ collection: collection, _id: _id })
            : rpc.emptyData({ collection: collection, clone: clonedFrom });

        Promise.all([
            rpcCache.collection({ collection: collection }),
            dataPromise,
        ]).then(([json, dataRes]) => {
            if (json?.result?.structure) {
                setStructure(json.result.structure);
            }


            setCollectionMenu(json?.result?.collectionMenu ?? null);

            if (json?.result?.collectionMenu?.allItems?.[0]) {
                setSelectMenu({
                    menu: json.result.collectionMenu.allItems[0],
                    relation: null,
                });
            }

            if (_id) {
                valuesRef.current = dataRes?.result?.data?.[0] ?? {};
                loadActions();
                rpc.dataSocials({ collection: collection, _id: _id }).then((data) => {
                    setSocials(data?.result ?? null);
                }).catch(() => {
                    setSocials(null);
                });
            } else {
                valuesRef.current = dataRes.result ?? {};
            }

            loadRelations();
        }).catch(() => {
            closeDialog(modalKey);
        }).finally(() => {
            setLoading(false);
        });

        if (_id) {
            rpc.collectionAccess({ collection: collection, ids: [_id] }).then((data) => {
                setCollectionAccess(data?.result ?? null);
            }).catch(() => {
                setCollectionAccess(null);
            });
        } else {
            rpc.collectionAccess({ collection: collection }).then((data) => {
                setCollectionAccess(data?.result ?? null);
            }).catch(() => {
                setCollectionAccess(null);
            });
        }
    }, [collection]);

    const isFormReady = !loading && !!structure && !!selectMenu?.menu?.group && !!collectionAccess;
    const isRelationReady = !loading && !!selectMenu?.relation?.collection;


    const [forceUpdateIncrement, setForceUpdateIncrement] = React.useState(0);

    const forceUpdateValues = (newData: any) => {
        valuesRef.current = newData;
        setForceUpdateIncrement((prev) => prev + 1);
    }


    const onSave = (action: 'save' | 'save_and_close' | 'save_and_add_new' | 'save_and_edit') => {


        if (!structure) {
            toast.error(Lang.key('error_saving'));
            return;
        }


        let valid = requiredValidation(valuesRef.current, structure, valuesRef.current, []);

        if (valid.length > 0) {


            let field = valid[0];





            toast.error(`${field} ${Lang.key('is_required')}`);
            return;


        }

        let loading = toast.loading(Lang.key('saving'));

        rpc.update({
            collection: collection,
            _ids: _id ? [_id] : undefined,
            values: valuesRef.current
        }).then((data) => {


            let newData = data?.result?.data?.[0] ?? null;



            toast.success(Lang.key('saved_successfully'));

            if (action === 'save_and_close') {
                closeDialog(modalKey);
            }

            if (action === 'save_and_add_new') {

                return;

                openDialog({
                    collection: collection,
                });

                closeDialog(modalKey);


                return;
                //TODO
            }
            if (action === 'save_and_edit') {

                if (!_id) {

                    openDialog({
                        collection: collection,
                        _id: data?.result?.data?.[0]?._id,
                    });

                    closeDialog(modalKey);

                } else {
                    forceUpdateValues(newData);
                }
                return;

                //TODO
            }
            if (action === 'save') {

                if (!_id) {

                    openDialog({
                        collection: collection,
                        _id: data?.result?.data?.[0]?._id,
                    });
                    closeDialog(modalKey);

                } else {
                    forceUpdateValues(newData);

                }

                return;
                //TODO
            }


        }).catch((error) => {
            toast.error(Lang.key('error_saving'));
        }).finally(() => {
            toast.dismiss(loading);
        });
    }

    const onDelete = () => {
        confirmAlertRef.current?.open({
            title: Lang.key('delete_item'),
            description: Lang.key('delete_item_description'),
            buttons: [
                { label: Lang.key('cancel'), onClick: () => { } },
                {
                    label: Lang.key('delete'), onClick: () => {

                        if (_id) {
                            rpc.deleteData({ collection: collection, _ids: [_id] }).then((data) => {
                                toast.success(Lang.key('deleted_successfully'));
                                closeDialog(modalKey);
                            });
                        }
                    }
                },
            ]
        });
    }

    const { isMobile } = useAppConfigStore();
    const { color } = useAppConfig();



    const onDoAction = useCallback((item: AdminActionMenuItemType) => {

        if (_id) {

            actionDialogRef.current?.open({
                collection: collection,
                action: item,
                ids: [_id],
                onSuccess: () => {

                    loadData();
                }
            });
        }
    }, [_id]);

    const onClone = () => {
        if (_id) {
            openDialog({
                modalKey: `collection_create_${collection}_cloned_from_${_id}`,
                collection: collection,
                clonedFrom: _id,
            });
        }
    }

    const { openTableDialog } = useAppConfig();
    const onOpenRelationTable = (item: CollectionRelationType) => {

        if (_id) {

            setSelectMenu({
                menu: null,
                relation: item,
            });

            // openTableDialog({ ...item, ids: [_id] })
        }
    }


    const [actions, setActions] = React.useState<AdminActionMenuItemType[]>([]);

    const formSkeleton = (
        <RowCSS className="w-full p-4">
            {[1, 2, 3, 4, 5].map((index) => (
                <ColCSS key={index} col={12} className='px-1'>
                    <Skeleton className="w-16 h-2 mt-2" />
                    <Skeleton className="w-full h-12 mt-1" />
                </ColCSS>
            ))}
        </RowCSS>
    );


    if (isMobile) {






        return <MobilePopup opened={true} onBackdropClick={() => closeDialog(modalKey)}>

            <MobilePage>
                <MobileNavbar
                    right={<MobileLink
                        onClick={() => closeDialog(modalKey)}
                    ><XIcon /></MobileLink>}
                    title={<LL value={structure?.title} />}
                    subtitle={_id ? Lang.key('edit_item') : Lang.key('create_item')}

                    subnavbar={collectionMenu?.allItems && collectionMenu?.allItems?.length > 1 &&
                        <div className=' inline-flex gap-2 overflow-x-scroll  py-2 overflow-y-hidden'>


                            {collectionMenu?.menu?.map((item) => {
                                if (item.children) {


                                    return <>
                                        {item.children.map((item, index) => {



                                            return <MobileLink

                                                style={{
                                                    borderColor: selectMenu?.menu?.key == item.key ? color : undefined
                                                }}

                                                onClick={() => {
                                                    if (item.key) {
                                                        onSelectMenu(item.key);
                                                    }
                                                }} className="whitespace-nowrap border-1 border-gray-200 rounded-md px-2 py-1">
                                                <LL value={item.title} />
                                            </MobileLink>



                                        })}

                                    </>


                                }

                                return <MobileLink
                                    style={{
                                        borderColor: selectMenu?.menu?.key == item.key ? color : undefined
                                    }}
                                    className="whitespace-nowrap"
                                    onClick={() => {
                                        if (item.key) {
                                            onSelectMenu(item.key);
                                        }
                                    }}>
                                    <LL value={item.title} />
                                </MobileLink>





                            })}


                        </div>
                    }

                />
                {!isFormReady && !isRelationReady && formSkeleton}
                {isFormReady && <CollectionFields


                    groupKey={selectMenu?.menu?.group}
                    onlyShow={!!_id ? !collectionAccess?.canUpdate : !collectionAccess?.canCreate}

                    structure={structure}
                    valuesRef={valuesRef}
                />}

                {isRelationReady && <>

                    <CollectionTable
                        collection={selectMenu?.relation?.collection ?? ''}
                        defaultFilter={{
                            [selectMenu?.relation?.key!]: { in: [_id] },
                        }}
                    />
                </>}



                <AnyDropdownMenu
                    className="fixed left-1/2 bottom-safe-4 transform -translate-x-1/2 z-20"
                    menu={[
                        {
                            htmlIcon: <SaveIcon />,
                            disabled: loading || !collectionAccess?.buttons?.showSaveButton,
                            label: Lang.key("save"),
                            click: () => {
                                onSave('save');
                            }
                        },
                        {
                            label: Lang.key("actions"),
                            disabled: loading || !collectionAccess?.buttons?.showActionButton || !actions.length,

                            submenu: actions.map((item) => {
                                return {
                                    htmlIcon: <ServerIcon icon={item?.icon} />,
                                    label: !!item.title ? <LL value={item.title} /> : item.key,
                                    click: () => {
                                        onDoAction(item);
                                    }
                                }
                            })
                        },
                        {
                            htmlIcon: <CopyIcon />,
                            disabled: loading || !collectionAccess?.buttons?.showCloneButton,
                            label: Lang.key("copy_item"),
                            click: () => {
                                onClone()
                            }
                        },
                        {
                            htmlIcon: <ArchiveIcon />,
                            label: Lang.key("copy_item_id"),
                            disabled: loading || !collectionAccess?.buttons?.showCopyButton,
                            click: () => {
                                if (_id) {
                                    copyTextToClipboard(_id);
                                }
                            }
                        },
                        {
                            htmlIcon: hideTips ? <EyeIcon /> : <EyeOffIcon />,
                            label: hideTips ? Lang.key("show_tips") : Lang.key("hide_tips"),
                            click: () => {
                                setHideTips(!hideTips);
                            }
                        },

                        {
                            htmlIcon: <Trash2Icon />,
                            disabled: loading || !collectionAccess?.buttons?.showDeleteButton,
                            label: Lang.key("delete"),
                            click: () => {
                                onDelete();
                            }
                        },



                    ]}
                >
                    <MobileFab

                        icon={<MoreHorizontalIcon className='size-5' />}
                    />
                </AnyDropdownMenu>


            </MobilePage>

        </MobilePopup>
    }

    return (

        <SystemWindowDialog
            open={true}
            onOpenChange={(open) => {
                if (!open) {
                    closeDialog(modalKey);
                }
            }}
            title={<LL value={structure?.title} />}
            width="80vw"
            height="80vh"
            allowFullscreen
            bodyClassName="p-0 overflow-hidden"
        >
            <Grid className='h-full w-full'>
                <GridCol width="300px" className=' py-2 px-1 border-r'>

                    <GridRow autoSize>

                        <ButtonGroup className='w-full'>
                            <Button

                                onClick={() => closeDialog(modalKey)}
                                className='w-full flex-1'
                                variant="outline">{Lang.key('close')} <Kbd>Shift + X</Kbd></Button>
                            <DropdownMenu>
                                <DropdownMenuTrigger asChild>
                                    <Button
                                        disabled={loading}
                                        variant="outline" size="icon"
                                        tooltip={Lang.key('more_options')}
                                        aria-label={Lang.key('more_options')}>
                                        <MoreHorizontalIcon />
                                    </Button>
                                </DropdownMenuTrigger>
                                <DropdownMenuContent align="end">
                                    <DropdownMenuGroup>
                                        <DropdownMenuItem
                                            disabled={loading || !collectionAccess?.buttons?.showCloneButton}
                                            onClick={() => {

                                                onClone()

                                            }}>
                                            <CopyIcon />
                                            {Lang.key("copy_item")}
                                        </DropdownMenuItem>
                                        <DropdownMenuItem
                                            disabled={loading || !collectionAccess?.buttons?.showCopyButton}
                                            onClick={() => {
                                                if (_id) {
                                                    copyTextToClipboard(_id);
                                                }
                                            }}>
                                            <ArchiveIcon />
                                            {Lang.key("copy_item_id")}
                                        </DropdownMenuItem>
                                    </DropdownMenuGroup>
                                    <DropdownMenuSeparator />
                                    <DropdownMenuGroup>
                                        <DropdownMenuItem

                                            onClick={() => {

                                                setHideTips(!hideTips);

                                            }}
                                        >
                                            {hideTips ? <EyeIcon /> : <EyeOffIcon />}
                                            {hideTips ? Lang.key("show_tips") : Lang.key("hide_tips")}
                                        </DropdownMenuItem>
                                    </DropdownMenuGroup>
                                    <DropdownMenuSeparator />

                                    <DropdownMenuGroup>
                                        <DropdownMenuItem
                                            disabled={loading || !collectionAccess?.buttons?.showDeleteButton}
                                            onClick={() => onDelete()}
                                            variant="destructive">
                                            <Trash2Icon />
                                            {Lang.key("delete")}
                                        </DropdownMenuItem>
                                    </DropdownMenuGroup>
                                </DropdownMenuContent>
                            </DropdownMenu>
                        </ButtonGroup>

                    </GridRow>

                    <GridRow className='px-2 py-4 flex flex-col gap-2'>


                        {collectionMenu?.menu?.map((item) => {
                            if (item.children) {


                                return <div className='mb-4'>
                                    <Label><LL value={item.title} /></Label>
                                    {item.children.map((item, index) => {


                                        let keyIndex: number | null = index + 1;

                                        if (keyIndex == 10) {
                                            keyIndex = 0;
                                        }

                                        if (keyIndex > 10) {
                                            keyIndex = null;
                                        }

                                        return <MenuItem

                                            hotkey={keyIndex !== null ? `Shift+${keyIndex}` : undefined}
                                            active={selectMenu?.menu?.key == item.key}
                                            media={<ServerIcon
                                                color={selectMenu?.menu?.key == item.key ? color : undefined}
                                                icon={item.icon} />}
                                            label={<span
                                                style={{
                                                    opacity: selectMenu?.menu?.key == item.key ? 1 : 0.8
                                                }}
                                            ><LL value={item.title} /></span>}
                                            onClick={() => {
                                                if (item.key) {
                                                    onSelectMenu(item.key);
                                                }
                                            }}
                                            key={item.key}>

                                        </MenuItem>
                                    })}

                                </div>


                            }

                            return <MenuItem
                                onClick={() => {
                                    if (item.key) {
                                        onSelectMenu(item.key);
                                    }
                                }}

                                media={<ServerIcon
                                    color={selectMenu?.menu?.key == item.key ? color : undefined}
                                    icon={item.icon} />}
                                label={<span
                                    style={{
                                        opacity: selectMenu?.menu?.key == item.key ? 1 : 0.8
                                    }}
                                ><LL value={item.title} /></span>}
                                active={selectMenu?.menu?.key == item.key}

                                key={item.key}>

                            </MenuItem>



                        })}

                        {collectionAccess?.buttons?.showActionButton && !!actions.length && <div className='mb-4'>
                            <Label>{Lang.key('actions')}</Label>
                            {actions.map((item) => {
                                return <MenuItem
                                    media={<ServerIcon icon={item?.icon} />}
                                    onClick={() => {
                                        onDoAction(item);
                                    }}

                                    key={item.key}
                                    label={!!item.title ? <LL value={item.title} /> : item.key}>
                                </MenuItem>
                            })}

                        </div>}




                        {collectionAccess?.buttons?.showRelationButton && <>


                            {relationsLoading && <>


                                <Skeleton
                                    className="w-full h-12"
                                />
                            </>}


                            {!relationsLoading && !!relations?.length && <div className='mb-4'>
                                <Label>{Lang.key('relations_collection')}</Label>
                                {relations.map((item) => {
                                    return <MenuItem
                                        media={<ServerIcon icon={item.icon} />}
                                        label={<LL value={item.title} />}
                                        subtitle={<LL value={item.subtitle} />}
                                        active={selectMenu?.relation?.collection == item.collection && selectMenu?.relation?.key == item.key}
                                        key={item.key}
                                        onClick={() => {
                                            onOpenRelationTable(item);
                                        }}
                                    >
                                    </MenuItem>
                                })}
                            </div>}

                        </>}





                        {!!socials?.length && <div className='mb-4'>
                            <Label>{Lang.key('linked_social_media_accounts')}</Label>
                            {socials?.map((item) => {
                                return <Button
                                    key={item.soc}
                                    onClick={() => {
                                        socialInfoDialogRef.current?.open({
                                            social: item,
                                        });
                                    }}
                                    className='w-full'
                                    size="sm"
                                    variant="outline">{Lang.key('social_' + (item.type ?? item.soc))}</Button>
                            })}

                        </div>}







                    </GridRow>

                    <GridRow autoSize >

                        <ButtonGroup

                            className='w-full'>
                            <Button
                                disabled={loading || !collectionAccess?.buttons?.showSaveButton}
                                onClick={() => onSave('save')}
                                className='w-full flex-1'
                                variant="outline"><SaveIcon />
                                {Lang.key('save')} <Kbd>Shift + S</Kbd></Button>
                            <DropdownMenu>
                                <DropdownMenuTrigger asChild>
                                    <Button
                                        disabled={loading}
                                        variant="outline" size="icon"
                                        tooltip={Lang.key('more_options')}
                                        aria-label={Lang.key('more_options')}>
                                        <MoreHorizontalIcon />
                                    </Button>
                                </DropdownMenuTrigger>
                                <DropdownMenuContent align="end" >
                                    <DropdownMenuGroup>
                                        <DropdownMenuItem
                                            disabled={loading || !collectionAccess?.buttons?.showSaveButton}
                                            onClick={() => onSave('save_and_close')}>
                                            <SaveIcon />
                                            {Lang.key("save_and_close")}
                                        </DropdownMenuItem>
                                        {/*<DropdownMenuItem
                                                disabled={loading || !buttonsShow.showCreateButton()}
                                                onClick={() => onSave('save_and_add_new')}>
                                                <PlusIcon />
                                                {Lang.key("save_and_add_new")}
                                            </DropdownMenuItem>*/}
                                        <DropdownMenuItem
                                            disabled={loading || !collectionAccess?.buttons?.showSaveButton}
                                            onClick={() => onSave('save_and_edit')}>
                                            <PencilIcon />
                                            {Lang.key("save_and_edit")}
                                        </DropdownMenuItem>
                                    </DropdownMenuGroup>
                                    <DropdownMenuGroup>
                                        <DropdownMenuItem
                                            disabled={loading || !collectionAccess?.buttons?.showDeleteButton}
                                            onClick={() => onDelete()}
                                            variant="destructive">
                                            <Trash2Icon />{Lang.key("delete")}
                                        </DropdownMenuItem>
                                    </DropdownMenuGroup>

                                </DropdownMenuContent>
                            </DropdownMenu>
                        </ButtonGroup>



                    </GridRow>

                </GridCol>
                <GridCol>


                    {!isFormReady && !isRelationReady && formSkeleton}
                    {isFormReady && <CollectionFields
                        key={`${forceUpdateIncrement}-${selectMenu?.menu?.group}`}


                        onlyShow={!!_id ? !collectionAccess?.canUpdate : !collectionAccess?.canCreate}

                        groupKey={selectMenu?.menu?.group}
                        structure={structure}
                        valuesRef={valuesRef}
                    />}

                    {isRelationReady && <>

                        <CollectionTable

                            key={forceUpdateIncrement}
                            collection={selectMenu?.relation?.collection ?? ''}



                            defaultFilter={{
                                [selectMenu?.relation?.key!]: { in: [_id] },
                            }}
                        />
                    </>}


                </GridCol>
            </Grid>


        </SystemWindowDialog>

    )


}

export default CollectionView;