import {
    BackgroundImage, Badge,
    Box, Button, Center, FileButton,
    Flex,
    Grid,
    Group, Image,
    LoadingOverlay, Overlay,
    Paper,
    rem, Stack,
    Stepper,
    TextInput, ThemeIcon, Title, Text,
    Tooltip,
    useMantineTheme, Loader, Anchor, ScrollArea, Modal
} from "@mantine/core";
import {lazy, Suspense, useEffect, useState} from "@wordpress/element";
import {nextStep, prevStep} from "../../../features/onboard/onboardSlice";
import {saveBasicInfo} from "../../../features/config/configThunks";
import {notifications} from "@mantine/notifications";
import {
    IconAlertTriangle,
    IconCheck,
    IconHelpCircle,
    IconPointFilled,
    IconArrowRight,
    IconPhoto
} from "@tabler/icons-react";
import {useForm} from "@mantine/form";
import {useDispatch, useSelector} from "react-redux";
import {updateConfig} from "../../../features/config/configSlice";
import Confetti from "react-confetti";
import {useDisclosure, useViewportSize} from "@mantine/hooks";
import {fetchSupportPlugins} from "../../../features/supportPlugins/supportPluginsThunks";
import BlockActivityWaitLoader from "../../../utils/loader/BlockActivityWaitLoader";


const StepSelectApp = lazy(() => import('./StepSelectApp'));
const ThemeList = lazy(() => import('../theme/ThemeList'));

export default function OnboardModal(){
    const theme = useMantineTheme();
    const {height, width} = useViewportSize();

    const dispatch = useDispatch();

    const {config, loadingSupportPluginSlug} = useSelector(state => state.config);
    const {activeStep, totalStep} = useSelector(state => state.onboard);
    const {blockActivity} = useSelector(state => state.blockActivity)

    const [splashScreenImageUrl, setSplashScreenImageUrl] = useState(null);
    const [logoUrl, setLogoUrl] = useState(null);
    const [saving, handlersSaving] = useDisclosure(false);


    const form = useForm({
        initialValues: {
            user_name: config?.user_name,
            app_type: config?.app_type,
            app_name: config?.app_name,
            user_email: config?.user_email,
            website_link: config?.website_link,
        },
    });

    const handleSkipOnboard = () => dispatch(updateConfig({basic_info_tour_guide_modal: false}))

    const handleSaveBasicInfo = () => {
        handlersSaving.open();

        dispatch(saveBasicInfo(form.values))
            .unwrap()
            .then(() => dispatch(nextStep()))
            .catch(err => {
                notifications.show({
                    color: theme.colors.red[6],
                    title: 'Error',
                    message: err.message,
                    icon: <IconAlertTriangle size={rem(18)} />,
                    autoClose: 5000,
                });
            })
            .finally(() => handlersSaving.close())
    }

    const handleNextStep = () =>{
        dispatch(nextStep())
    }
    const handlePrevStep = () =>{
        dispatch(prevStep())
    }

    useEffect(() => {
        dispatch(fetchSupportPlugins())
    }, [dispatch]);
    return(
        <>
            <Modal
                pos="relative"
                opened={config?.basic_info_tour_guide_modal}
                onClose={handleSkipOnboard}
                title=""
                size="75%"
                scrollAreaComponent={ScrollArea.Autosize}
                withCloseButton={false}
                closeOnClickOutside={false}
            >
                {blockActivity && <BlockActivityWaitLoader/>}

                <Stepper
                    data-autofocus
                    active={activeStep}
                    size="xs"
                    h={630}
                    styles={{
                        steps: {
                            display: totalStep === activeStep ? 'none' : null,
                        }
                    }}
                >
                    <Stepper.Step label="Select App" description="" pos="relative">
                        <Suspense fallback={<LoadingOverlay visible={true} zIndex={1000} overlayProps={{ radius: "sm", blur: 5 }} loaderProps={{ size: 'sm' }} />}>
                            <StepSelectApp/>
                        </Suspense>
                    </Stepper.Step>

                    <Stepper.Step label="Theme Activation" description="" pos="relative">
                        <Suspense fallback={<LoadingOverlay visible={true} zIndex={1000} overlayProps={{ radius: "sm", blur: 5 }} loaderProps={{ size: 'sm' }} />}>
                            <ThemeList slideHeight={`61vh`}/>
                        </Suspense>
                    </Stepper.Step>

                    <Stepper.Step label="Basic Settings" description="">
                        <Grid gutter={50} h="inherit" justify="center" mx={100}>
                            <Grid.Col span={8} pl={50}>
                                <Paper
                                    radius="md"
                                    shadow="md"
                                    h="100%"
                                    p={50}
                                    withBorder={true}
                                >
                                    <TextInput
                                        label="Name"
                                        placeholder="Enter your full name"
                                        mb="lg"
                                        styles={{
                                            label: {
                                                color: 'var(--mantine-color-dark-5)'
                                            }
                                        }}
                                        {...form.getInputProps('user_name')}
                                    />
                                    <TextInput
                                        label="Email"
                                        placeholder="example@gmail.com"
                                        mb="lg"
                                        styles={{
                                            label: {
                                                color: 'var(--mantine-color-dark-5)'
                                            }
                                        }}
                                        {...form.getInputProps('user_email')}
                                    />
                                    <TextInput
                                        label="Website link"
                                        placeholder="www.yoursite.com"
                                        mb="lg"
                                        styles={{
                                            label: {
                                                color: 'var(--mantine-color-dark-5)'
                                            }
                                        }}
                                        {...form.getInputProps('website_link')}
                                    />
                                    <TextInput
                                        label="App name"
                                        placeholder="Appza"
                                        mb="lg"
                                        styles={{
                                            label: {
                                                color: 'var(--mantine-color-dark-5)'
                                            }
                                        }}
                                        {...form.getInputProps('app_name')}
                                    />

                                    <Box mt="xs">
                                        <Flex align="center" gap={5}>
                                            <Text size="sm" c={theme.colors.gray[8]}>Upload logo</Text>
                                            <Tooltip
                                                multiline
                                                w={250}
                                                color={theme.primaryColor}
                                                withArrow
                                                transitionProps={{ duration: 200 }}
                                                label="Upload your Android app logo. This logo will appear on the Google Play Store and represent your app. Recommended size: 512x512 pixels. File type: PNG (with a transparent background)"
                                            >
                                                <IconHelpCircle color={theme.colors.gray[5]} size={16}/>

                                            </Tooltip>
                                        </Flex>

                                        <FileButton
                                            disabled={false === config?.appza_is_premium}
                                            onChange={(file) => {
                                                form.setValues({appza_app_logo: file})
                                                setLogoUrl(URL.createObjectURL(file))

                                            }}
                                            accept="image/png"

                                        >
                                            {(props) => <Button
                                                {...props}
                                                fullWidth
                                                p={0}
                                                color={theme.colors.gray[7]}
                                                variant="outline"
                                                justify="flex-start"
                                                leftSection={
                                                    <Box bg={theme.colors.gray[2]} w={120} p="xs"><Text c="#475177" fw={500} size="sm">Choose File</Text></Box>
                                                }
                                                style={{
                                                    border: `1px solid ${theme.colors.gray[4]}`,
                                                }}
                                            >
                                                { form.values.appza_app_logo?
                                                    <Flex align="center" gap={5}><IconPhoto size={16}/> <Text fw={400} size="sm">{form.values.appza_app_logo.name}</Text></Flex> :
                                                    <Text fw={400} size="sm">No file chosen</Text>
                                                }
                                            </Button>
                                            }
                                        </FileButton>
                                        <Text size="xs" c="dimmed">Recommended size: 512x512 pixels, File type: PNG (with a transparent background)</Text>
                                    </Box>
                                    <Box mt="xs">
                                        <Flex align="center" gap={5}>
                                            <Text size="sm" c={theme.colors.gray[8]}>Upload splash screen</Text>
                                            <Tooltip
                                                multiline
                                                w={250}
                                                color={theme.primaryColor}
                                                withArrow
                                                transitionProps={{ duration: 200 }}
                                                label="Upload your Android app splash screen. This screen appears when your app is launched. Recommended size: 1920x1920 pixels. File type: PNG (with a transparent background)"
                                            >
                                                <IconHelpCircle color={theme.colors.gray[5]} size={16}/>

                                            </Tooltip>
                                        </Flex>

                                        <FileButton
                                            disabled={false === config?.appza_is_premium}
                                            onChange={(file) => {
                                                form.setValues({appza_app_splash_screen_image: file})
                                                setSplashScreenImageUrl(URL.createObjectURL(file))
                                            }}
                                            accept="image/png"

                                        >
                                            {(props) => <Button
                                                {...props}
                                                fullWidth
                                                p={0}
                                                color={theme.colors.gray[7]}
                                                variant="outline"
                                                justify="flex-start"
                                                leftSection={
                                                    <Box bg={theme.colors.gray[2]} w={120} p="xs"><Text c="#475177" fw={500} size="sm">Choose File</Text></Box>
                                                }
                                                style={{
                                                    border: `1px solid ${theme.colors.gray[4]}`,
                                                }}
                                            >
                                                { form.values.appza_app_splash_screen_image?
                                                    <Flex align="center" gap={5}><IconPhoto size={16}/> <Text fw={400} size="sm">{form.values.appza_app_splash_screen_image.name}</Text></Flex> :
                                                    <Text fw={400} size="sm">No file chosen</Text>
                                                }
                                            </Button>
                                            }
                                        </FileButton>
                                        <Text size="xs" c="dimmed">Recommended size: 1920x1920 pixels File type: PNG (with a transparent background)</Text>
                                    </Box>
                                </Paper>
                            </Grid.Col>
                            <Grid.Col span="auto">
                                <Paper radius="md" withBorder pos="relative">
                                    {
                                        false === config?.appza_is_premium && (
                                            <Overlay
                                                backgroundOpacity={0.05}
                                                blur={3}
                                                radius="md"
                                            >
                                                <Flex justify="center" align="center" mih={`100%`} direction="column">
                                                    <Text c={theme.primaryColor} lineClamp={2} ta="center" fw={700}>Required Premium Addon!</Text>
                                                    <Anchor href="http://lazycoders.co/appza" target="_blank"><Button>Get Premimum</Button></Anchor>
                                                </Flex>
                                            </Overlay>
                                        )
                                    }

                                    <BackgroundImage h={579} radius="md" src={splashScreenImageUrl || config?.media_urls?.appza_app_splash_screen_image} position="center" size="contain" repeat="no-repeat">

                                        <Flex
                                            direction="column"
                                            justify="space-between"
                                            align="center"
                                            p="xs"
                                            h="100%"
                                        >
                                            <Badge
                                                w="25%"
                                                p={0}
                                                color={theme.colors.dark[8]}
                                                size="sm"
                                                rightSection={<IconPointFilled color={theme.colors.gray[7]}/>}
                                                styles={{
                                                    section: {
                                                        padding: 0,
                                                    }
                                                }}
                                            >

                                            </Badge>

                                            <Flex direction="column" justify="center" align="center" gap="xs">
                                                {
                                                    (config?.media_urls?.appza_app_logo?.length > 0 && ! form.values.appza_app_logo) &&
                                                    <Image alt="App logo" fit="contain" w={200} h={100} src={config?.media_urls?.appza_app_logo} />
                                                }

                                                { form.values.appza_app_logo && <Image fit="cover" w={`80%`} h={100} src={logoUrl} /> }

                                                <Text
                                                    fw={600}
                                                    lineClamp={1}
                                                    py={2}
                                                    px="xs"
                                                    bg="white"
                                                    styles={{
                                                        root: {
                                                            borderRadius: theme.radius.lg,
                                                        }
                                                    }}
                                                >
                                                    {config?.app_name}
                                                </Text>

                                            </Flex>

                                            <Paper h={4} bg={theme.colors.gray[7]} w="30%" radius="xl"></Paper>

                                        </Flex>
                                    </BackgroundImage>
                                </Paper>

                            </Grid.Col>
                        </Grid>
                    </Stepper.Step>

                    <Stepper.Completed>
                        <Confetti
                            height={730}
                            width={width}
                        />
                        <Paper
                            radius="md"
                            p="xl"
                            mih={650}
                        >
                            <Center h={550}>
                                <Stack justify="center" align="center">
                                    <ThemeIcon
                                        radius="xl"
                                        size="xl"
                                        color="#475177"
                                    >
                                        <IconCheck style={{width: rem(24), height: rem(24)}}/>
                                    </ThemeIcon>
                                    <Title order={3} style={{ color: '#192655'}}>Thank you for joining us!</Title>
                                    <Text size="md" c="#192655">Your journey with Appza begins now.</Text>
                                    <Button rightSection={<IconArrowRight/>} onClick={handleSkipOnboard}>Start building your app now</Button>
                                </Stack>
                            </Center>
                        </Paper>
                    </Stepper.Completed>
                </Stepper>

                <Group justify="flex-end" mt="xl">
                    { activeStep !== totalStep && <Button variant="outline" disabled={loadingSupportPluginSlug.length > 0 || saving} onClick={handleSkipOnboard}>Skip</Button> }

                    { activeStep !== 0 && activeStep !== totalStep && <Button variant="default" disabled={saving} onClick={handlePrevStep}> Back</Button> }

                    { activeStep < 2  && <Button onClick={handleNextStep} disabled={loadingSupportPluginSlug.length > 0 || saving}>Next</Button> }
                    { activeStep === 2  && <Button onClick={handleSaveBasicInfo} disabled={saving} leftSection={saving ? <Loader size="xs" /> : null}>Save</Button> }

                </Group>

            </Modal>
        </>
    )
}