import {
    Button,
    Text,
    Image,
    Flex,
    Center,
    Overlay,
    rem,
    Loader,
    Modal,
    useMantineTheme, ActionIcon, Title, Divider, Group, BackgroundImage, Pill
} from "@mantine/core";
import {useHover, useDisclosure} from "@mantine/hooks";
import {notifications} from "@mantine/notifications";
import {IconAlertTriangle, IconCheck, IconEye, IconXboxX} from "@tabler/icons-react";
import {Carousel} from "@mantine/carousel";
import {modals} from "@mantine/modals";
import {useDispatch, useSelector} from "react-redux";
import {activateTheme, restoreTheme} from "../../../../features/themes/themeThunks";
import {fetchActiveTheme} from "../../../../features/themes/themeThunks";
import {setActiveScreen} from "../../../../features/screen/screenSlice";
import {setSelectedComponent} from "../../../../features/selectedComponent/selectedComponentSlice";
import {setBlockActivity} from "../../../../features/blockActivity/blockActivitySlice";
import {fetchBlockActivityStatus} from "../../../../features/blockActivity/blockActivityThunks";
const startPolling = (dispatch, theme) => {
    const pollInterval = setInterval(() => {
        dispatch(fetchBlockActivityStatus())
            .unwrap()
            .then((data) => {
                if (data.status === 'completed' || data.status === 'idle') {
                    clearInterval(pollInterval);
                    dispatch(setBlockActivity(false));
                    notifications.show({
                        color: theme.primaryColor,
                        title: 'Theme configured successfully!',
                        icon: <IconCheck style={{ width: rem(18), height: rem(18) }} />,
                        loading: false,
                        autoClose: 5000,
                        withCloseButton: true,
                    });
                    dispatch(fetchActiveTheme());

                } else if (data.status === 'failed') {
                    clearInterval(pollInterval);
                    dispatch(setBlockActivity(false));
                    notifications.show({
                        color: 'var(--mantine-color-red-9)',
                        title: 'Theme import failed. Please try again.',
                        icon: <IconAlertTriangle style={{ width: rem(18), height: rem(18) }} />,
                        loading: false,
                        autoClose: 5000,
                        withCloseButton: true,
                    });
                }
            })
            .catch(() => {
                // Keep polling on network errors
            });
    }, 5000); // Poll every 5 seconds
};

const _ThemeCard = ({themeData, slideHeight, isOnboarding}) => {

    const { hovered, ref} = useHover();
    const theme = useMantineTheme();
    const [previewModalOpened,togglePreviewModal] = useDisclosure(false);
    const [loading,toggleLoading] = useDisclosure(false);

    const dispatch = useDispatch();
    const {activeTheme} = useSelector(state => state.activeTheme);

    const handleRestoreTheme = () => {
        modals.openConfirmModal({
            title: '',
            centered: true,
            children: (
                <Flex justify="center" align="center" gap="sm" w={`100%`} direction="column">
                    <Group gap="xs">
                        <IconAlertTriangle color={theme.primaryColor}/>
                        <Text size="sm" fw={600}>Reset Theme</Text>
                    </Group>
                    <Divider size="xs" w={`100%`} />
                    <Text size="sm" c="#4D4D4D" ta="center" my={30}>
                        Are You Sure! After reset your customization will be removed for this theme.
                    </Text>
                </Flex>

            ),
            labels: {cancel: "No, Keep It.", confirm: "Yes, Delete !"},
            // confirmProps: {color: 'var(--mantine-color-gray-2)'},
            cancelProps: {bg: theme.primaryColor, c: "#ffffff", style: {borderColor: theme.primaryColor}},
            confirmProps: {bg: 'var(--mantine-color-gray-2)', c: '#202020'},
            withCloseButton: false,
            groupProps: {justify: 'center'},
            overlayProps: {
                blur: 1,
            },
            closeOnClickOutside: false,
            modalProps:{
                body: {
                    padding: 0
                }
            },
            onCancel: () => console.log('Cancel'),
            onConfirm: () => {
                dispatch(setBlockActivity(true));

                dispatch(restoreTheme(themeData?.slug))
                    .unwrap()
                    .then(res => {
                        if (res.status === 202) {

                            startPolling(dispatch, theme);
                        } else {
                            dispatch(setBlockActivity(false));
                            notifications.show({
                                color: theme.primaryColor,
                                title: 'Restored!',
                                icon: <IconCheck style={{ width: rem(18), height: rem(18) }} />,
                                loading: false,
                                autoClose: 5000,
                                withCloseButton: true,
                            });
                        }
                    })
                    .catch(function (err) {
                        console.log(err);

                        dispatch(setBlockActivity(false));

                        notifications.show({
                            color: 'var(--mantine-color-red-9)',
                            title: err.message,
                            icon: <IconAlertTriangle style={{ width: rem(18), height: rem(18) }} />,
                            loading: false,
                            autoClose: 5000,
                            withCloseButton: true,
                        });

                    })
            }
        });

    }

    const handleActivateTheme = () => {
        dispatch(setBlockActivity(true));

        dispatch(activateTheme(themeData?.slug))
            .unwrap()
            .then((res) => {
                if (res.status === 202) {
                    startPolling(dispatch, theme);
                } else {
                    dispatch(setBlockActivity(false));
                    notifications.show({
                        color: theme.primaryColor,
                        title: 'Activated!',
                        icon: <IconCheck style={{ width: rem(18), height: rem(18) }} />,
                        loading: false,
                        autoClose: 5000,
                        withCloseButton: true,
                    });
                }
            })
            .catch(err => {
                console.log(err);
                dispatch(setBlockActivity(false));

                notifications.show({
                    color: theme.colors.red[7],
                    title: err?.message || 'Something went wrong, please try again!',
                    icon: <IconAlertTriangle style={{ width: rem(18), height: rem(18) }} />,
                    loading: false,
                    autoClose: 5000,
                    withCloseButton: true,
                });
            })
            .finally(() => {
                dispatch(setActiveScreen('home-page'))
                dispatch(setSelectedComponent(null))
            })

    };



    return(
        <>
            <Carousel.Slide>
                <BackgroundImage
                    ref={ref}
                    src={themeData?.image_url}
                    pos="relative"
                    h={slideHeight}
                    radius="md"
                    style={{
                        backgroundRepeat: 'no-repeat',
                        backgroundSize: 'contain',
                        border: `1px solid ${theme.colors.gray[2]}`,
                    }}
                >
                    {
                        hovered && activeTheme?.slug !== themeData?.slug && (
                            <Overlay radius="md">
                                <Center><Pill mt="xl">{themeData?.name}</Pill></Center>

                                <Flex
                                    align="center"
                                    justify="center"
                                    gap="md"
                                    mih={`80%`}
                                >
                                    <Button leftSection={<IconEye color={theme.colors.dark[9]} stroke={1}/>} onClick={togglePreviewModal.open} disabled={loading} size="xs" color="#FFF4E6"><Text c={theme.colors.dark[9]} fw={500}>Preview</Text></Button>
                                    <Button size="xs" disabled={loading} leftSection={loading && <Loader size="xs"/>} onClick={handleActivateTheme}><Text c="white">Active</Text></Button>

                                </Flex>
                            </Overlay>
                        )
                    }
                    {
                        activeTheme?.slug === themeData?.slug && (
                            <Overlay radius="md">
                                <Center><Pill mt="xl">{themeData?.name}</Pill></Center>
                                <Flex
                                    align="center"
                                    justify="center"
                                    gap="md"
                                    mih={`80%`}
                                    wrap="wrap"

                                >
                                    <Button leftSection={<IconEye color={theme.colors.dark[9]} stroke={1}/>} onClick={togglePreviewModal.open} size="xs" color="#FFF4E6"><Text c={theme.colors.dark[9]} fw={500}>Preview</Text></Button>
                                    <Button size="xs" disabled ><Text c={theme.colors.dark[9]}>Activated</Text></Button>

                                    {!isOnboarding &&
                                        <Button
                                            w="30%"
                                            variant="outline"
                                            size="xs"
                                            disabled={loading}
                                            leftSection={loading && <Loader size="xs"/>}
                                            onClick={handleRestoreTheme}
                                        >
                                            <Text c="white">Reset</Text>
                                        </Button>
                                    }


                                </Flex>
                            </Overlay>
                        )
                    }
                </BackgroundImage>

            </Carousel.Slide>

            <Modal
                opened={previewModalOpened}
                onClose={togglePreviewModal.close}
                title=""
                centered
                size="50%"
                closeOnClickOutside={false}
                withCloseButton={false}
            >
                <Modal.Header p={0}>
                    <Modal.Title>
                        <Title order={4} data-autofocus>{themeData.name} Preview</Title>
                    </Modal.Title>
                    <Modal.CloseButton>
                        <ActionIcon
                            variant="light"
                            color={theme.colors.gray[5]}
                            onClick={togglePreviewModal.close}
                        >
                            <IconXboxX stroke={1.5} />
                        </ActionIcon>
                    </Modal.CloseButton>
                </Modal.Header>
                {
                    themeData.pages_preview.length === 0 && (
                        <Center>
                            <Text bg={theme.primaryColor + '.0'} p="xs">No preview available</Text>
                        </Center>
                    )
                }
                {
                    themeData.pages_preview.length > 0 && (
                        <Carousel
                            slideSize="33.333333%"
                            slideGap="xs"
                            align="start"
                            height="100%"
                            styles={{
                                control: {
                                    backgroundColor: theme.primaryColor,
                                    color: 'var(--mantine-color-black)',
                                }
                            }}

                        >
                            {
                                themeData?.pages_preview?.map((image_url, index) => (
                                    <Carousel.Slide key={index}>
                                        <Image
                                            fit="contain"
                                            src={image_url}
                                            style={{
                                                boxShadow: '0px 0px 10px 0px var(--mantine-color-gray-4)',
                                            }}
                                        />
                                    </Carousel.Slide>
                                ))
                            }
                        </Carousel>
                    )
                }

            </Modal>

        </>
    );
}
_ThemeCard.defaultProps = {
    isOnboarding: true,
}
export default _ThemeCard;


