import { Navigate } from "react-router-dom";
import { PacketResult, ResultCode } from "@/app/providers/ProtocolProvider/protocol/packets/packet.result";
import { modals } from "@mantine/modals";
import { Button, Flex, Text } from "@mantine/core";
import { usePrivateKeyHash } from "@/app/providers/AccountProvider/usePrivateKeyHash";
import { usePacket } from "@/app/providers/ProtocolProvider/usePacket";

interface PrivateViewProps {
    children: React.ReactNode;
}

export function PrivateView(props : PrivateViewProps) {
    const privateKey = usePrivateKeyHash();

    if(privateKey.trim() == "") {
        return <Navigate to="/" />;
    }

    const openModal = (title : string, message : string) => {
        modals.open({
            title: title,
            children: (
                <>
                <Text size="sm">
                    {message}
                </Text>
                <Flex align={'center'} justify={'flex-end'}>
                    <Button color={'red'} variant={'subtle'} onClick={() => modals.closeAll()} mt="md">
                        Close
                    </Button>
                </Flex>
                </>
            ), 
            centered: true, 
            withCloseButton: true,
            closeOnClickOutside: true,
            closeOnEscape: true
        });
    };
    
    usePacket(0x2, (packet : PacketResult) => {
        switch (packet.getResultCode()) {
            case ResultCode.SUCCESS:
                break;
            case ResultCode.ERROR:
                openModal("Error", "Unknown error from server, please try again");
                break;
            case ResultCode.USERNAME_TAKEN:
                openModal("Error", "Username is already taken");
                break;
            case ResultCode.INVALID:
                openModal("Error", "Invalid data provided");
                break;
        }
    });

    return (
        <>
            {privateKey ? (
                props.children
            ) : (
                <Navigate to="/" />
            )}
        </>
    );
}
