import {
    Box,
    Center, Flex,
    LoadingOverlay, Paper, rem, ScrollArea, Text, ThemeIcon, Tooltip, useMantineTheme
} from "@mantine/core";
import {useListState, useViewportSize} from "@mantine/hooks";
import {lazy, Suspense, useEffect, useRef} from "@wordpress/element";
import {DragDropContext, Draggable, Droppable} from "@hello-pangea/dnd";
import {useDispatch, useSelector} from "react-redux";
import {
    fetchScreenComponents,
    reorderComponents
} from "../../../features/pageComponents/componentsThunks";
import {notifications} from "@mantine/notifications";
import {IconAlertTriangle, IconCheck, IconSpeakerphone} from "@tabler/icons-react";

const _Component = lazy(() => import('./_Component'));
const Appbar = lazy(() => import('./Appbar'));
const Navbar = lazy(() => import('./Navbar'));

const MobileRender = () => {
    const {height, width} = useViewportSize();
    const viewport = useRef(null);
    const itemRefs = useRef([]);
    const theme = useMantineTheme();



    const dispatch = useDispatch();
    const [orderComponents, handlersOrderComponents] = useListState([]);
    const {screenProperty, components, recentAddedComponentId, loading} = useSelector((state => state.components));
    const {activeScreen} = useSelector((state => state.screens));
    const {activeTheme} = useSelector((state => state.activeTheme));
    const {activeSupportPlugin} = useSelector((state => state.config));
    const {copySelectedComponent, isSaved} = useSelector((state => state.selectedComponent));

    const screenHeight = height < 850 ? (height - 300) : 502;
    const deviceWidth = height < 850 ? 350 : 400;

    const WARNING_NOTIFICATION_ID = 'scroll-disabled-warning';

    const handleSaveComponentOrder = (result) => {

        const { destination, source } = result;
        if (!destination || destination.index === source.index) return;

        handlersOrderComponents.reorder({ from: source.index, to: destination.index });

        // Dispatch to persist order
        const reorderedList = [...orderComponents];
        const moved = reorderedList.splice(source.index, 1)[0];
        reorderedList.splice(destination.index, 0, moved);

        dispatch(reorderComponents(reorderedList));

    }
    const handleComponentPosition = (id) => {
        const item = itemRefs.current[id];
        const scrollContainer = viewport.current;


        if (item && scrollContainer) {
            const itemTop = item.offsetTop;
            const itemHeight = item.offsetHeight;
            const containerHeight = scrollContainer.offsetHeight;

            const scrollTo = itemTop - (containerHeight / 2) + (itemHeight / 2);
            // scrollContainer.scrollTo({ top: scrollTo, behavior: 'smooth' });
            scrollContainer.scrollTo({ top: itemTop, behavior: 'smooth' });
        }
    };

    const handleWheel = (event) => {
        event.preventDefault();

        if (document.getElementById(WARNING_NOTIFICATION_ID)) {
            notifications.update({
                id: WARNING_NOTIFICATION_ID,
                color: theme.colors.red[6],
                title: '',
                message: <Flex direction="column">
                    <Text size="xs" ta="center">Scrolling is disabled while you're editing components</Text>
                    <Text size="xs" ta="center">To exit edit mode, close the <Text span fw={600} fs="italic">edit panel</Text> on your right</Text>
                </Flex>,
                icon: <IconAlertTriangle style={{width: rem(18), height: rem(18)}}/>,
                loading: false,
                autoClose: 2000,
                withCloseButton: false,
                position: 'bottom-center',
                styles: {
                    root: {
                        left: '13%',
                        width: 360
                    }
                }
            });
        } else {
            // Show it the first time
            notifications.show({
                id: WARNING_NOTIFICATION_ID,
                color: theme.colors.red[6],
                title: '',
                message: <Flex direction="column">
                    <Text size="xs" ta="center">Scrolling is disabled while you're editing components</Text>
                    <Text size="xs" ta="center">To exit edit mode, close the <Text span fw={600} fs="italic">edit panel</Text> on your right</Text>
                </Flex>,
                icon: <IconAlertTriangle style={{width: rem(18), height: rem(18)}}/>,
                loading: false,
                autoClose: 2000,
                withCloseButton: false,
                position: 'bottom-center',
                styles: {
                    root: {
                        left: '13%',
                        width: 360
                    }
                }
            });
        }
    }

    useEffect(() => {
        dispatch(fetchScreenComponents(activeScreen));

    }, [dispatch, activeScreen, activeTheme, activeSupportPlugin, isSaved]);


    useEffect(() => {
        handlersOrderComponents.setState(components)
    }, [components]);



    useEffect(() => {
        recentAddedComponentId && setTimeout(() => {
            viewport.current.scrollTo({ top: viewport.current.scrollHeight, behavior: 'smooth' });
        },2000)
    }, [recentAddedComponentId])

    useEffect(() => {

        if (null === copySelectedComponent || 'component' !== copySelectedComponent.mode) viewport.current.style.overflowY = 'auto'; // Show scrollbar when no component is selected

        if (null !== copySelectedComponent && 'component' === copySelectedComponent.mode) {
            handleComponentPosition(copySelectedComponent.id);

            viewport.current.style.overflowY = 'hidden'; // Hide scrollbar during scroll
            viewport.current.addEventListener('wheel', handleWheel, { passive: false });

        }

        return () => {
            if (viewport.current) {
                viewport.current.removeEventListener('wheel', handleWheel);
            }
        };

    }, [copySelectedComponent])

    return(
        
        <Tooltip
            label={screenProperty?.customize_properties?.static_screen_message}
            color="#475177"
            position="right"
            offset={{ crossAxis: -200 }}
            multiline
            withArrow
            w={200}
            zIndex={0}
            opened={'static' == screenProperty?.customize_properties?.screen_status}
        >
            <Box
                w={deviceWidth}
                p={3}
                m={20}
                style={{
                    flexDirection: "column",
                    alignItems: "center",
                    backgroundColor: "var(--mantine-color-gray-0)",
                    borderRadius: 25,
                    boxShadow: "0px 0px 20px 3px var(--mantine-color-gray-5)",
                }}
            >
                <Center bg="gray.8" style={{ width: "100%", height: "50px", borderRadius: "25px 25px 0px 0px", zIndex: 999 }} >
                    <Box bg="var(--mantine-color-gray-7)" w={15} h={15} mr={5} style={{borderRadius: "25px",}}/>
                    <Box bg="var(--mantine-color-gray-6)" w={50} h={5} style={{borderRadius: "25px",}}/>
                </Center>
                <Flex
                    direction="column"
                    justify="space-between"
                    gap={0}
                    bg={screenProperty?.customize_properties?.page_decoration?.background_color}
                    style={{
                        width: "100%",
                        border: "5px solid var(--mantine-color-gray-8)",
                    }}
                    pos="relative"
                    h={height < 850 ? (height - 300) : 654}
                >
                    <Suspense
                        fallback={
                            <LoadingOverlay visible={true} zIndex={10} overlayProps={{ radius: "sm", blur: 5 }} loaderProps={{size: 'xs' }}/>
                        }
                    >
                        <Appbar/>
                    </Suspense>


                    <ScrollArea
                        h={ screenHeight }
                        scrollbarSize={3}
                        type={`never`}
                        scrollbars="y"
                        viewportRef={viewport}
                        styles={{
                            root: {
                                backgroundImage: 'static' == screenProperty?.customize_properties?.screen_status ? `url(${screenProperty?.customize_properties?.static_screen_image})` : 'none',
                                backgroundSize: '100% 100%',
                                backgroundRepeat: 'no-repeat',
                            }
                        }}
                    >
                        <LoadingOverlay visible={loading} overlayProps={{radius: "sm", blur: 5}} loaderProps={{size: 'sm'}} zIndex={10}/>

                        {/*{
                        'static' == screenProperty?.customize_properties?.screen_status && (
                            <Center h={screenHeight}>
                                <Paper p="sm" withBorder shadow="md" bg={theme.primaryColor}>
                                    {screenProperty?.customize_properties?.static_screen_message}
                                </Paper>
                            </Center>
                        )
                    }*/}

                        {
                            'static' !== screenProperty?.customize_properties?.screen_status && (

                                <DragDropContext onDragEnd={handleSaveComponentOrder}>
                                    <Droppable droppableId="dnd-list" direction="vertical">
                                        {(provided) => (
                                            <Box {...provided.droppableProps} ref={provided.innerRef}>
                                                {
                                                    orderComponents?.map((component, index) => (
                                                        <div ref={(el) => (itemRefs.current[component.id] = el)}>
                                                            <Draggable key={component.id} index={index} draggableId={component.id} >
                                                                {(provided, snapshot) => (
                                                                    <Box {...provided.draggableProps} ref={provided.innerRef}>

                                                                        <Suspense
                                                                            fallback={
                                                                                <LoadingOverlay visible={true} overlayProps={{radius: "sm", blur: 5}} loaderProps={{size: 'sm'}} zIndex={10}/>
                                                                            }
                                                                        >
                                                                            <_Component key={index} provided={provided} component={component}/>
                                                                        </Suspense>


                                                                    </Box>
                                                                )}
                                                            </Draggable>
                                                        </div>

                                                    ))
                                                }
                                                {
                                                    orderComponents?.length === 0 && (
                                                        <Center h={ height < 850 ? (height - 300) : 500 }>
                                                            <Text align="center" size="xs" weight={700} c={theme.primaryColor}>This page doesn't have any component now.</Text>
                                                        </Center>
                                                    )
                                                }

                                                {provided.placeholder}
                                            </Box>
                                        )}
                                    </Droppable>
                                </DragDropContext>

                            )
                        }

                    </ScrollArea>


                    <Suspense
                        fallback={ <LoadingOverlay visible={true} zIndex={10} overlayProps={{ radius: "sm", blur: 5 }} loaderProps={{size: 'xs' }}/>}
                    >
                        <Navbar/>
                    </Suspense>

                </Flex>


                <Center bg="gray.8" style={{ width: "100%", height: "50px", borderRadius: "0px 0px 25px 25px", }} >
                    <Box bg="var(--mantine-color-gray-3)" w={65} h={35} style={{borderRadius: "15px",}}/>
                </Center>
            </Box>

        </Tooltip>
        

    );
}

export default MobileRender;