import {
    Box,
    Button,
    Center,
    ColorInput,
    Flex,
    Grid,
    Group,
    Image, Loader, LoadingOverlay,
    rem,
    Select,
    Text,
    TextInput,
    useMantineTheme
} from "@mantine/core";
import {IconAlertTriangle, IconCheck, IconChevronDown, IconPencilMinus, IconServer} from "@tabler/icons-react";
import GlobalMediaUploadAreaPlaceholder from "../../../../assets/images/global_media_upload_area_placeholder.png";
import {useDispatch, useSelector} from "react-redux";
import {updateConfig} from "../../../features/config/configSlice";
import { useState} from "@wordpress/element";
import {saveConfig} from "../../../features/config/configThunks";
import {notifications} from "@mantine/notifications";
import {useDisclosure} from "@mantine/hooks";

export default function GeneralSettings(){
    const theme = useMantineTheme();
    const dispatch = useDispatch();
    const {config, loading, error} = useSelector(state => state.config);

    const [changeConfig, setChangeConfig] = useState(null);
    const [submitted, handlersSubmit] = useDisclosure(false);

    const handleChange = (value) => {
        setChangeConfig({ ...changeConfig, ...value})
        dispatch(updateConfig(value))
    }
    const handleSave = () => {
        if (null === changeConfig) return;
        handlersSubmit.open();
        dispatch(saveConfig(changeConfig))
            .unwrap()
            .then(res => {
                setChangeConfig(null);
                notifications.show({
                    color: 'var(--mantine-color-orange-7)',
                    title: 'Updated!',
                    icon: <IconCheck style={{ width: rem(18), height: rem(18) }} />,
                    loading: false,
                    autoClose: 1000,
                    withCloseButton: true,
                });

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

    return(
        <Box pos="relative">
            <LoadingOverlay visible={loading} zIndex={1000} overlayProps={{ radius: "sm", blur: 5 }} loaderProps={{ size: 'sm' }} />
            <Grid gutter={0} mt="xs" h={`95%`}>
                <Grid.Col span={6}>
                    <TextInput
                        data-autofocus
                        label=""
                        placeholder="App Name"
                        rightSection={<IconPencilMinus style={{ width: rem(16), height: rem(16) }}/>}
                        defaultValue={config?.app_name}
                        rightSectionPointerEvents="none"
                        onChange={(event) => handleChange({app_name: event.currentTarget.value})}
                        mb="xs"

                    />

                    <Select
                        label=""
                        searchable
                        placeholder="Primary Font"
                        data={[
                            {value: 'Open Sans', label: 'Open Sans'},
                            {value: 'Roboto', label: 'Roboto'},
                            {value: 'Poppins', label: 'Poppins'},
                        ]}
                        rightSection={<IconChevronDown style={{ width: rem(16), height: rem(16) }}/>}
                        rightSectionPointerEvents="none"
                        value={config?.primary_font}
                        onChange={value => handleChange({primary_font: value})}
                        allowDeselect={false}
                        nothingFoundMessage="Nothing found..."
                        maxDropdownHeight={200}
                        mb="xs"


                    />
                    <Select
                        label=""
                        searchable
                        placeholder="Secondary Font"
                        data={[
                            {value: 'Open Sans', label: 'Open Sans'},
                            {value: 'Roboto', label: 'Roboto'},
                            {value: 'Poppins', label: 'Poppins'},
                        ]}
                        rightSection={<IconChevronDown style={{ width: rem(16), height: rem(16) }}/>}
                        value={config?.secondary_font}
                        onChange={value => handleChange({secondary_font: value})}

                        allowDeselect={false}
                        nothingFoundMessage="Nothing found..."
                        maxDropdownHeight={200}
                        mb="xs"

                    />
                    <Flex
                        align="center"
                        justify="space-between"
                        mb="xs"
                    >
                        <Text fz={14}>Primary Font Color</Text>
                        <ColorInput
                            styles={{
                                wrapper: {
                                    padding: 5,
                                    border: "var(--mantine-color-gray-2) 1px solid",
                                    borderRadius: "var(--mantine-radius-sm)"
                                },
                                input: {
                                    backgroundColor: config?.primary_font_color,
                                    height: 36,
                                    width: 36,
                                    color: "transparent",
                                },
                            }}
                            defaultValue=""
                            value=""
                            variant="unstyled"
                            disallowInput
                            leftSection={` `}
                            leftSectionWidth={0}
                            rightSection={` `}
                            rightSectionWidth={0}
                            onChangeEnd={(value) => handleChange({primary_font_color: value})}
                            // swatches={['#383838', '#868e96', '#fa5252', '#e64980', '#be4bdb', '#7950f2', '#4c6ef5', '#228be6', '#15aabf', '#12b886', '#40c057', '#82c91e', '#fab005', '#fd7e14']}
                        />
                    </Flex>
                    <Flex
                        align="center"
                        justify="space-between"
                        mb="xs"
                    >
                        <Text fz={14}>Secondary Font Color</Text>
                        <ColorInput
                            styles={{
                                wrapper: {
                                    padding: 5,
                                    border: "var(--mantine-color-gray-2) 1px solid",
                                    borderRadius: "var(--mantine-radius-sm)"
                                },
                                input: {
                                    backgroundColor: config?.secondary_font_color,
                                    height: 36,
                                    width: 36,
                                    color: "transparent",
                                },
                            }}
                            defaultValue=""
                            value=""
                            variant="unstyled"
                            disallowInput
                            leftSection={` `}
                            leftSectionWidth={0}
                            rightSection={` `}
                            rightSectionWidth={0}
                            onChangeEnd={(value) => handleChange({secondary_font_color: value})}
                            // swatches={['#383838', '#868e96', '#fa5252', '#e64980', '#be4bdb', '#7950f2', '#4c6ef5', '#228be6', '#15aabf', '#12b886', '#40c057', '#82c91e', '#fab005', '#fd7e14']}
                        />
                    </Flex>
                </Grid.Col>
                <Grid.Col span="auto">
                    <Center>
                        <Box w={380}>
                            {window.appzaPremium && <window.appzaPremium.GlobalFileUpload theme={theme} />}
                            {!window.appzaPremium && <Image w={400} h={680} fit="contain" src={GlobalMediaUploadAreaPlaceholder} />}
                        </Box>
                    </Center>
                </Grid.Col>
            </Grid>

            <Group justify="flex-end">
                <Button onClick={handleSave} disabled={submitted} leftSection={submitted ? <Loader size="xs"/> : <IconServer/>} >Save</Button>
            </Group>
        </Box>
    )
}