import {
    AspectRatio,
    Box, Button,
    Center, Divider,
    Flex,
    Grid, Group, Image,
    List,
    LoadingOverlay,
    Paper, rem,
    Switch, Text,
    ThemeIcon,
    Tooltip, useMantineTheme
} from "@mantine/core";
import {useDispatch, useSelector} from "react-redux";
import {fetchSupportPlugins} from "../../../features/supportPlugins/supportPluginsThunks";
import {modals} from "@mantine/modals";
import {IconAlertTriangle, IconCheck, IconReload, IconSpeakerphone} from "@tabler/icons-react";
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 StepSelectApp(){
    const theme = useMantineTheme();
    const dispatch = useDispatch();
    const {config, loadingSupportPluginSlug} = useSelector(state => state.config);
    const {supportPlugins, loading} = useSelector(state => state.supportPlugins);

    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,
                            });
                        }
                    })
                    .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,
                        });
                    });
            }
        });
    }


    return(
        <Grid justify="center" align="center" gutter="xl">
            <Grid.Col span={8}>
                <Center mt="md"><Text fw={700} mb="xs" c="#192655">Appza Guideline Tutorial</Text></Center>
                <AspectRatio ratio={16 /10} data-autofocus>
                    <iframe
                        src="https://www.youtube.com/embed/fPsk1PSH6iw?si=W6dhy-K7sdeH_0my"
                        title="Appza Guideline Video"
                        style={{border: 0}}
                        allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                    />
                </AspectRatio>
            </Grid.Col>
            <Grid.Col span="auto" p="xl">
                <Center mt="md"><Text fw={700} mb="xs" c="#192655">Select App</Text></Center>
                <Box
                    p="lg"
                    style={{
                        borderRadius: 'var(--mantine-radius-md)',
                        boxShadow: 'var(--mantine-shadow-md)',
                        border: '1px solid var(--mantine-color-gray-1)',
                    }}
                    pos="relative"
                >
                    <List spacing="xl">
                        <LoadingOverlay visible={loading} zIndex={1000} overlayProps={{ radius: "sm", blur: 5 }} loaderProps={{ size: 'sm' }} />

                        {supportPlugins.length === 0 && <Center h={300}><Button variant="outline" size="xs" onClick={handleReloadSupportPlugins} leftSection={<IconReload />}>Reload</Button></Center>}

                        {
                            supportPlugins.length !== 0 && supportPlugins?.map((plugin, index) => (
                                <Tooltip
                                    disabled={false == plugin?.is_disable}
                                    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,
                                        }
                                    }}
                                >
                                    <List.Item 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',
                                                }
                                            }}
                                        />
                                    </List.Item>
                                </Tooltip>
                            ))
                        }
                    </List>
                </Box>
            </Grid.Col>
        </Grid>
    )
}