import {
    Box,
    Button,
    Center, Divider,
    Flex,
    Group,
    Image,
    LoadingOverlay,
    Paper, rem,
    Switch,
    Text,
    ThemeIcon,
    Tooltip, useMantineTheme
} from "@mantine/core";
import {IconAlertTriangle, IconArrowRight, IconCheck, IconReload, IconSpeakerphone} from "@tabler/icons-react";
import {useDispatch, useSelector} from "react-redux";
import {fetchSupportPlugins} from "../../../features/supportPlugins/supportPluginsThunks";
import {useEffect, useState} from "@wordpress/element";
import {modals} from "@mantine/modals";
import {activateSupportPlugin} from "../../../features/config/configThunks";
import {notifications} from "@mantine/notifications";
import {setBlockActivity} from "../../../features/blockActivity/blockActivitySlice";
import {fetchBlockActivityStatus} from "../../../features/blockActivity/blockActivityThunks";
import {fetchActiveTheme} from "../../../features/themes/themeThunks";
import {updateActiveSupportPlugin} from "../../../features/config/configSlice";




const startPolling = (dispatch, theme, config) => {
    const pollInterval = setInterval(() => {
        dispatch(fetchBlockActivityStatus())
            .unwrap()
            .then((data) => {
                if (data.status === 'completed' || data.status === 'idle') {
                    clearInterval(pollInterval);
                    dispatch(setBlockActivity(false));
                    dispatch(updateActiveSupportPlugin(config?.extensions[0] || '')); // Update active support plugin in the store
                    dispatch(fetchActiveTheme());

                    notifications.show({
                        color: theme.primaryColor,
                        title: 'Theme configured successfully!',
                        icon: <IconCheck style={{ width: rem(18), height: rem(18) }} />,
                        loading: false,
                        autoClose: 5000,
                        withCloseButton: true,
                    });


                } 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
};


export default function IntegrationSettings({handlersSettingsModal, handlersThemesModal}){
    const theme = useMantineTheme();
    const dispatch = useDispatch();

    const {supportPlugins, loading} = useSelector(state => state.supportPlugins);
    const {config, loadingSupportPluginSlug, loading: configLoading} = useSelector(state => state.config);

    const [isSupportPluginChange, setIsSupportPluginChange] = useState(false);

    const handleReloadSupportPlugins = () => dispatch(fetchSupportPlugins())

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

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

                dispatch(activateSupportPlugin(params))
                    .unwrap()
                    .then((res) => {
                        if (res.status === 202) {

                            startPolling(dispatch, theme, config);
                        } else {
                            dispatch(setBlockActivity(false));
                            notifications.show({
                                color: theme.primaryColor,
                                title: 'Configured!',
                                icon: <IconCheck style={{ width: rem(18), height: rem(18) }} />,
                                loading: false,
                                autoClose: 5000,
                                withCloseButton: true,
                            });
                        }
                        setIsSupportPluginChange(true)
                    })
                    .catch((err) => {
                        console.error(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,
                        });
                    });
            }
        });
    }

    useEffect(() => {
        dispatch(fetchSupportPlugins())
    }, [dispatch]);

    return(
        <Box pos="relative">
            <LoadingOverlay visible={loading} zIndex={1000} overlayProps={{ radius: "sm", blur: 5 }} loaderProps={{ size: 'sm' }} />
            {supportPlugins.length === 0 && <Center py={10}><Button variant="outline" size="xs" onClick={handleReloadSupportPlugins} leftSection={<IconReload />}>Reload</Button></Center>}

            {
                supportPlugins.length !== 0 && (
                    <Flex justify="space-between" align="center" py={10}>
                        {
                            supportPlugins?.map((plugin, index) => (
                                <Tooltip
                                    key={plugin?.slug}
                                    disabled={false == plugin?.is_disable}
                                    position="bottom"
                                    color="white"
                                    label={
                                        <Paper withBorder p="xs" radius="md">
                                            <Flex align="center" gap="xs">
                                                <ThemeIcon
                                                    radius="xl"
                                                    variant="gradient"
                                                    gradient={{ from: 'indigo', to: 'violet', deg: 173 }}
                                                    p={4}
                                                >
                                                    <IconSpeakerphone style={{transform: 'rotate(-25deg)'}}/>
                                                </ThemeIcon>
                                                <Box>
                                                    <Text c={theme.colors.dark[9]} fw={500}>Upcoming</Text>
                                                    <Text c="dimmed">This feature is coming soon!</Text>
                                                </Box>
                                            </Flex>
                                        </Paper>
                                    }
                                    styles={{
                                        tooltip: {
                                            padding: 0,
                                        }
                                    }}
                                >
                                    <Box pos="relative">
                                        <LoadingOverlay visible={loadingSupportPluginSlug === plugin.slug || false} zIndex={1000} overlayProps={{ radius: "sm", blur: 5 }} loaderProps={{size: 'xs' }} />

                                        <Switch
                                            key={plugin.slug}
                                            disabled={
                                                plugin?.is_disable ||
                                                (loadingSupportPluginSlug.length > 0 && loadingSupportPluginSlug !== plugin.slug && 'wordpress' !== plugin.slug) // All will be disabled except 'wordpress' when one is loading
                                            }
                                            checked={config?.extensions?.includes(plugin.slug) || 'wordpress' === plugin.slug}
                                            onChange={
                                                (e) => 'wordpress' !== plugin.slug && handleActivateSupportPlugin({[plugin.slug]: e.target.checked})
                                            }
                                            size="xs"
                                            label={
                                                <Flex justify="flex-start" align="center" gap={6}>
                                                    <Box bg="gray.2" h={36} w={36} p={5} style={{ borderRadius: 'var(--mantine-radius-sm)'}}>
                                                        <Image h="100%" w="100%" fit="contain" src={plugin.image}/>
                                                    </Box>
                                                    <Text size="sm" fw={600}>{plugin.name}</Text>
                                                </Flex>
                                            }
                                            radius="sm"
                                            styles={{
                                                body: {
                                                    alignItems: 'center',
                                                    padding: 5,
                                                    boxShadow: 'var(--mantine-shadow-md)',
                                                    borderRadius: 'var(--mantine-radius-sm)',
                                                    border: 'var(--mantine-color-gray-2) 1px solid',

                                                }
                                            }}
                                        />
                                    </Box>
                                </Tooltip>
                            ))
                        }
                    </Flex>
                )
            }
            <Box>
                <Group gap={2}>
                    <IconSpeakerphone color={theme.primaryColor}/>
                    <Text c={theme.primaryColor} fs="italic">Currently, Only one extension can be activated with Wordpress Core!</Text>
                </Group>
            </Box>

            {isSupportPluginChange &&
                <Paper
                    bg={theme.colors.gray[0]}
                    p="xs"
                    withBorder
                >
                    <Flex
                        justify="space-between"
                        align="center"
                    >
                        <Text>Please Go through the themes of your selected addons, Active a theme to customize your app.</Text>
                        <Button
                            onClick={() => {
                                handlersThemesModal.open();
                                handlersSettingsModal.close();
                            }}
                            rightSection={<IconArrowRight />}
                        >
                            <Text fw={600}>Explore Themes</Text>
                        </Button>
                    </Flex>
                </Paper>
            }
        </Box>
    )
}