import {Box, Button, Grid, Group, Loader, rem, Stack, Text, TextInput, Title, useMantineTheme} from "@mantine/core";
import {
    IconAlertTriangle, IconBrandAndroid,
    IconBrandApple, IconCheck,
    IconCloudUpload, IconConfetti,
    IconFileCertificate, IconServer, IconSpeakerphone,
    IconUpload,
    IconX
} from "@tabler/icons-react";
import {Dropzone} from "@mantine/dropzone";
import {notifications} from "@mantine/notifications";
import {useForm} from "@mantine/form";
import {useDispatch, useSelector} from "react-redux";
import {fetchConfig, saveIosAppStoreConfig} from "../../../features/config/configThunks";
import {useEffect} from "@wordpress/element";
import {useDisclosure} from "@mantine/hooks";

export default function AppStoreSettings(){
    const theme = useMantineTheme();
    const dispatch = useDispatch();
    const {config} = useSelector(state => state.config);
    const [submitted, handlersSubmit] = useDisclosure(false);


    const iosForm = useForm({
        initialValues: {
            appza_ios_issuer_id: config?.appza_ios_issuer_id,
            appza_ios_key_id: config?.appza_ios_key_id,
            appza_ios_team_id: config?.appza_ios_team_id,
            appza_ios_p8_file: '',
        },

        validate: {
            // ios_issuer_id: isNotEmpty('Put the ID!'),
            // ios_key_id: isNotEmpty('Put the key!'),
            // ios_p8_file: isNotEmpty('Put the file!'),
        },
    });

    const handleSave = () => {
        handlersSubmit.open();
        const notificationId = notifications.show({
            color: 'var(--mantine-color-orange-2)',
            loading: true,
            title: 'Processing...',
            autoClose: false,
            withCloseButton: false,
        });


        dispatch(saveIosAppStoreConfig(iosForm.values))
            .unwrap()
            .then(res => {
                notifications.update({
                    id: notificationId,
                    color: 'var(--mantine-color-orange-7)',
                    title: 'Updated!',
                    icon: <IconCheck style={{ width: rem(18), height: rem(18) }} />,
                    loading: false,
                    autoClose: 5000,
                    withCloseButton: true,
                })
            })
            .catch(function (err) {
                console.log(err);
                notifications.update({
                    id: notificationId,
                    color: 'var(--mantine-color-red-9)',
                    title: err.message,
                    icon: <IconAlertTriangle style={{ width: rem(18), height: rem(18) }} />,
                    loading: false,
                    autoClose: 5000,
                    withCloseButton: true,
                });
            })
            .finally(() => handlersSubmit.close())
    }


/*    useEffect(() => {
        dispatch(fetchConfig())
    }, [dispatch]);*/

    return(
        <>
            <Group gap={2} p={2} mb="xs" bg={theme.primaryColor + '.0'} style={{borderRadius: 'var(--mantine-radius-sm)'}}>
                <IconBrandApple color={theme.primaryColor}/>
                <Title c={theme.primaryColor} order={5}>iOS</Title>
            </Group>
            <Box component="form" onSubmit={iosForm.onSubmit(handleSave)}>
                <Grid>
                    <Grid.Col span={6}>
                        {/*<TextInput
                                    label="App Store Name"
                                    placeholder="Enter Store Name"
                                    defaultValue={settingsData?.appza_ios_app_store_name}
                                    {...iosForm.getInputProps('appza_ios_app_store_name')}
                                />*/}
                        <TextInput
                            label="Issuer ID"
                            placeholder="Enter Issuer ID"
                            defaultValue={config?.appza_ios_issuer_id}
                            {...iosForm.getInputProps('appza_ios_issuer_id')}
                        />
                        <TextInput
                            label="Key ID"
                            placeholder="Enter Key ID"
                            defaultValue={config?.appza_ios_key_id}
                            {...iosForm.getInputProps('appza_ios_key_id')}
                        />
                        <TextInput
                            label="Team ID"
                            placeholder="Enter Team ID"
                            defaultValue={config?.appza_ios_team_id}
                            {...iosForm.getInputProps('appza_ios_team_id')}
                        />
                    </Grid.Col>
                    <Grid.Col span="auto">
                        <Dropzone
                            onDrop={(file) => {
                                iosForm.setValues({...iosForm.values, appza_ios_p8_file: file[0]})
                            }}

                            onReject={(file) => {
                                notifications.show({
                                    title: 'Only .p8 file!',
                                    color: 'var(--mantine-color-red-9)',
                                    autoClose: 5000,
                                    icon: <IconAlertTriangle style={{width: rem(18), height: rem(18)}}/>


                                })
                            }}

                            maxSize={1024 ** 2}
                            accept={{
                                'application/pkcs8' : ['.p8']
                            }}
                            style={{border: '2px dashed var(--mantine-color-orange-4)'}}
                            mb="xs"
                        >
                            <Stack gap="sm" align="center" justify="center" mih={200} style={{pointerEvents: 'none'}}>
                                <Dropzone.Accept>
                                    <IconUpload
                                        size={50}
                                        color='var(--mantine-color-blue-6)'
                                        stroke={1.5}
                                    />
                                </Dropzone.Accept>
                                <Dropzone.Reject>
                                    <IconX
                                        size={50}
                                        color='var(--mantine-color-red-6)'
                                        stroke={1.5}
                                    />
                                </Dropzone.Reject>
                                <Dropzone.Idle>

                                    {
                                        !!!iosForm.values.appza_ios_p8_file && config?.appza_ios_p8_file_content?.length === 0 &&
                                        <IconCloudUpload size={50} color='var(--mantine-color-dimmed)' stroke={1.5} />
                                    }
                                    {
                                        iosForm.values.appza_ios_p8_file &&
                                        <Group justify="center" gap={2}>
                                            <IconFileCertificate color={theme.primaryColor} size={57}/>
                                            <Text size="md" fw={700} inline>{iosForm.values.appza_ios_p8_file.name}</Text>
                                        </Group>
                                    }

                                    {
                                        !!!iosForm.values.appza_ios_p8_file && config?.appza_ios_p8_file_content?.length > 0 &&
                                        <Group justify="center" gap={2}>
                                            <IconFileCertificate color={theme.primaryColor} size={57}/>
                                            <Text size="md" fw={700} inline>{config?.appza_ios_p8_file_name}</Text>
                                        </Group>
                                    }

                                </Dropzone.Idle>
                                <Text size="xl" inline>Drag File or <span style={{color: 'var(--mantine-color-orange-4)'}}>Upload</span></Text>
                                <Text size="md" fw={700} inline>(only .p8 file)</Text>
                            </Stack>
                        </Dropzone>
                    </Grid.Col>
                </Grid>
                <Group justify="flex-end">
                    <Button type="submit" disabled={submitted} leftSection={submitted ? <Loader size="xs"/>: <IconServer/>} >Save</Button>
                </Group>
            </Box>
            <Group gap={2} p={2} mb="xs" mt="xs" bg={theme.primaryColor + '.0'} style={{borderRadius: 'var(--mantine-radius-sm)'}}>
                <IconBrandAndroid color={theme.primaryColor}/>
                <Title c={theme.primaryColor} order={5}>Android</Title>
            </Group>
            <Box>
                <Group gap={2}>
                    <IconSpeakerphone color={theme.primaryColor}/>
                    <Text c={theme.primaryColor} fs="italic">Do not need any configuration for android!</Text>
                    <IconConfetti color={theme.primaryColor} />
                </Group>
            </Box>
        </>
    )
}