import {
    Anchor,
    Box,
    Button, Divider, Flex, Grid,
    Group, Image, Loader, Paper,
    rem, ScrollArea, Switch, Tabs,
    Text,
    TextInput,
    Title,
    Tooltip,
    useMantineTheme
} from "@mantine/core";
import {
    IconAlertTriangle,
    IconCheck,
    IconHelpCircle, IconServer
} from "@tabler/icons-react";
import {notifications} from "@mantine/notifications";
import {isNotEmpty, useForm} from "@mantine/form";
import {useDispatch, useSelector} from "react-redux";
import {saveSocialLoginConfig} from "../../../features/config/configThunks";
import {useDisclosure, useViewportSize} from "@mantine/hooks";
import WebClientId1_1 from "../../../../assets/images/web-client-id-step-1.1.png";
import WebClientId1_2 from "../../../../assets/images/web-client-id-step-1.2.png";
import WebClientId1_3 from "../../../../assets/images/web-client-id-step-1.3.png";
import WebClientId1_4 from "../../../../assets/images/web-client-id-step-1.4.png";
import WebClientId2_1 from "../../../../assets/images/web-client-id-step-2.1.png";
import WebClientId2_2 from "../../../../assets/images/web-client-id-step-2.2.png";
import WebClientId3_1 from "../../../../assets/images/web-client-id-step-3.1.png";
import WebClientId3_2 from "../../../../assets/images/web-client-id-step-3.2.png";
import WebClientId4_1 from "../../../../assets/images/web-client-id-step-4.1.png";
import WebClientId4_2 from "../../../../assets/images/web-client-id-step-4.2.png";
import WebClientId4_3 from "../../../../assets/images/web-client-id-step-4.3.png";
import WebClientId5_1 from "../../../../assets/images/web-client-id-step-5.1.png";
import WebClientId5_2 from "../../../../assets/images/web-client-id-step-5.2.png";
import WebClientId5_3 from "../../../../assets/images/web-client-id-step-5.3.png";
import IosClientId5_1 from "../../../../assets/images/ios-client-id-step-5.1.png";
import IosClientId5_2 from "../../../../assets/images/ios-client-id-step-5.2.png";
import IosClientId5_3 from "../../../../assets/images/ios-client-id-step-5.3.png";




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

    const socialLoginConfigForm = useForm({
        initialValues: {
            appza_social_login_status: config?.appza_social_login_status || false,
            appza_google_login_web_client_id_status: config?.appza_google_login_web_client_id_status || false,
            appza_google_login_ios_client_id_status: config?.appza_google_login_ios_client_id_status || false,
            appza_google_web_client_id: config?.appza_google_web_client_id,
            appza_google_ios_client_id: config?.appza_google_ios_client_id,
        },

        validate: {
            appza_google_web_client_id: isNotEmpty('Required!'),
            appza_google_ios_client_id: isNotEmpty('Required!'),
        },
    });

    const handleSave = () => {

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


        dispatch(saveSocialLoginConfig(socialLoginConfigForm.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())
    }

    return(
        <>
            <Box component="form" onSubmit={socialLoginConfigForm.onSubmit(handleSave)}>

                <Grid mt="sm">
                    <Grid.Col span={6}>
                        <Paper withBorder shadow="sm" p="sm" mih={height - 300}>
                            <Group justify="space-between" py="md">
                                <Title order={5}>Social Login</Title>
                                <Switch
                                    {...socialLoginConfigForm.getInputProps('appza_social_login_status', { type: 'checkbox' })}
                                    labelPosition="left"
                                    size="xs"
                                    label={
                                        <Flex align="center" gap={5}>
                                            <Text size="sm">Button</Text>
                                            <Tooltip
                                                multiline
                                                color={theme.primaryColor}
                                                withArrow
                                                transitionProps={{ duration: 200 }}
                                                label="Toggle will show  “This button will turn the ‘Login with Google’ option on or off in the app."
                                            >
                                                <IconHelpCircle color={theme.colors.gray[5]} size={16}/>

                                            </Tooltip>
                                        </Flex>
                                    }
                                    radius="sm"
                                    color="green"
                                />
                            </Group>
                            <Divider/>

                            <Title order={5}>Google Login</Title>

                            {/*<Box component="form" onSubmit={socialLoginConfigForm.onSubmit(handleSave)}>*/}
                            <TextInput
                                label={
                                    <Flex align="center" justify="space-between">
                                        <Group gap={5}>
                                            <Text size="sm">Web Client ID <Text span c={theme.colors.red[7]}>*</Text></Text>
                                            <Tooltip
                                                multiline
                                                color={theme.primaryColor}
                                                withArrow
                                                transitionProps={{ duration: 200 }}
                                                label=""
                                            >
                                                <IconHelpCircle color={theme.colors.gray[5]} size={16}/>

                                            </Tooltip>
                                        </Group>
                                        <Switch
                                            {...socialLoginConfigForm.getInputProps('appza_google_login_web_client_id_status', { type: 'checkbox' })}
                                            size="xs"
                                            label=""
                                            radius="sm"
                                        />
                                    </Flex>
                                }
                                styles={{
                                    label: {
                                        width: '100%',
                                    }
                                }}
                                placeholder="227576826412-4rh3d6dit1mg5dlj9n5agg4.apps.googleusercontent.com"
                                // defaultValue={config?.appza_web_client_id}
                                {...socialLoginConfigForm.getInputProps('appza_google_web_client_id')}
                            />
                            <TextInput
                                mt="sm"
                                label={
                                    <Flex align="center" justify="space-between">
                                        <Group gap={5}>
                                            <Text size="sm">IOS Client ID <Text span c={theme.colors.red[7]}>*</Text></Text>
                                            <Tooltip
                                                multiline
                                                color={theme.primaryColor}
                                                withArrow
                                                transitionProps={{ duration: 200 }}
                                                label=""
                                            >
                                                <IconHelpCircle color={theme.colors.gray[5]} size={16}/>

                                            </Tooltip>
                                        </Group>
                                        <Switch
                                            {...socialLoginConfigForm.getInputProps('appza_google_login_ios_client_id_status', { type: 'checkbox' })}
                                            size="xs"
                                            label=""
                                            radius="sm"
                                        />
                                    </Flex>
                                }
                                styles={{
                                    label: {
                                        width: '100%',
                                    }
                                }}
                                placeholder="227576826412-unkqlibf0dttl7n0nkqn7bvc.apps.googleusercontent.com"
                                // defaultValue={config?.appza_ios_client_id}
                                {...socialLoginConfigForm.getInputProps('appza_google_ios_client_id')}
                            />
                        </Paper>
                    </Grid.Col>
                    <Grid.Col span="auto">
                        <Tabs
                            defaultValue="web-client-id"
                            variant="pills"
                            color="#475177"
                            styles={{
                                tab: {
                                    border: '1px solid #4D4D4D',
                                }
                            }}
                        >
                            <Tabs.List grow>
                                <Tabs.Tab value="web-client-id">Web Client ID</Tabs.Tab>
                                <Tabs.Tab value="ios-client-id">iOS Client ID</Tabs.Tab>
                            </Tabs.List>

                            <Tabs.Panel value="web-client-id">
                                <Paper withBorder shadow="sm" p="sm" mt="sm">
                                    <ScrollArea h={height - 374} scrollbarSize={3} type="always" offsetScrollbars>
                                        <Title order={4} c="">Google OAuth Setup — Web Client ID</Title>

                                        <Title order={5} my="xs">Step 1 — Create a Google Cloud Project</Title>
                                        <Text>Open this URL in your browser: <Anchor href="https://console.cloud.google.com/welcome/new" target="_blank">https://console.cloud.google.com/welcome/new</Anchor></Text>
                                        <Image src={WebClientId1_1} alt="Step 1" />
                                        <Text>Click <Text span fw="bold">Select a project</Text> at the top of the page.</Text>
                                        <Image src={WebClientId1_2} alt="Step 1" />
                                        <Text>In the popup, click <Text span fw="bold">New Project</Text>.</Text>
                                        <Image src={WebClientId1_3} alt="Step 1" />
                                        <Text>Enter a project name and click <Text span fw="bold">Create</Text>.</Text>
                                        <Image src={WebClientId1_4} alt="Step 1" />


                                        <Title order={5} my="xs">Step 2 — Open the Google Auth Platform</Title>
                                        <Text>Once the project is created, select it from the project list.</Text>
                                        <Text>In the top search bar, type: <Text span fw="bold">google auth platform</Text></Text>
                                        <Text>Click <Text span fw="bold">Google Auth Platform</Text> from the search results.</Text>
                                        <Image src={WebClientId2_1} alt="Step 2" />
                                        <Text>You should now see the Google Auth Platform page:</Text>
                                        <Image src={WebClientId2_2} alt="Step 2" />


                                        <Title order={5} my="xs">Step 3 — Configure the OAuth Consent Screen</Title>
                                        <Text>Click <Text span fw="bold">Get started</Text> and fill in the required information.</Text>
                                        <Image src={WebClientId3_1} alt="Step 3" />
                                        <Text>In the <Text span fw="bold">Audience</Text> section, select <Text span fw="bold">External</Text>.</Text>
                                        <Text>Fill in the remaining fields, then click <Text span fw="bold">Create</Text>.</Text>
                                        <Text>Open the <Text span fw="bold">Audience</Text> section again and <Text span fw="bold">Publish</Text> the app.</Text>
                                        <Image src={WebClientId3_2} alt="Step 3" />


                                        <Title order={5} my="xs">Step 4 — Add the Required Scopes</Title>
                                        <Text>Open the <Text span fw="bold">Data access</Text> section and click <Text span fw="bold">Add or remove scopes</Text>.</Text>
                                        <Image src={WebClientId4_1} alt="Step 4" />
                                        <Text>From the scope list, select these two scopes:</Text>
                                        <Text fw="bold">- .../auth/userinfo.email</Text>
                                        <Text fw="bold">- .../auth/userinfo.profile</Text>
                                        <Text>Then click <Text span fw="bold">Update</Text>.</Text>
                                        <Image src={WebClientId4_2} alt="Step 4" />
                                        <Text>Back on the <Text span fw="bold">Data access</Text> tab, click <Text span fw="bold">Save</Text>.</Text>
                                        <Image src={WebClientId4_3} alt="Step 4" />


                                        <Title order={5} my="xs">Step 5 — Create the Web OAuth Client</Title>
                                        <Text>Open the <Text span fw="bold">Clients</Text> section and click <Text span fw="bold">Create client</Text>.</Text>
                                        <Image src={WebClientId5_1} alt="Step 5" />
                                        <Text>From the <Text span fw="bold">Application type</Text> dropdown, select <Text span fw="bold">Web application</Text>.</Text>
                                        <Text>Fill in the required fields.</Text>
                                        <Image src={WebClientId5_2} alt="Step 5" />
                                        <Text>Click <Text span fw="bold">Save</Text>, then copy the <Text span fw="bold">Client ID</Text>.</Text>
                                        <Text><Text span fw="bold">Important:</Text> copy the <Text span fw="bold">Client ID</Text>, NOT the <Text span fw="bold">Client Secret</Text>.</Text>
                                        <Image src={WebClientId5_3} alt="Step 5" />

                                        <Title order={5} my="xs">Done</Title>
                                        <Text>Paste the client id on the following <Text span fw="bold">Web Client Id</Text> field.</Text>
                                    </ScrollArea>
                                </Paper>
                            </Tabs.Panel>
                            <Tabs.Panel value="ios-client-id">
                                <Paper withBorder shadow="sm" p="sm" mt="sm">
                                    <ScrollArea h={height - 374} scrollbarSize={3} type="always" offsetScrollbars>
                                        <Title order={4} c="">Google OAuth Setup — iOS Client ID</Title>
                                        <Text fs="italic" fz="sm" c="dimmed" style={{borderLeft: '2px solid #1a73e8', paddingLeft: 5}}>Before doing this, you must already have a Google Cloud project with the OAuth consent screen configured (audience set to External, app published, and the userinfo.email + userinfo.profile scopes added). If you have not done that yet, follow Steps 1 to 4 in the "Google OAuth Setup - Web Client ID" guide first.</Text>

                                        <Title order={5} my="xs">Step 5 — Create the iOS OAuth Client</Title>
                                        <Text>Open the <Text span fw="bold">Clients</Text> section and click <Text span fw="bold">Create client</Text>.</Text>
                                        <Image src={IosClientId5_1} alt="Step 5" />
                                        <Text>From the <Text span fw="bold">Application type</Text> dropdown, select <Text span fw="bold">iOS</Text>.</Text>
                                        <Text>Fill in the form. Use the <Text span fw="bold">bundle ID</Text> we provided you.</Text>
                                        <Image src={IosClientId5_2} alt="Step 5" />
                                        <Text>Click <Text span fw="bold">Create</Text>, then copy the <Text span fw="bold">iOS Client ID</Text>.</Text>
                                        <Image src={IosClientId5_3} alt="Step 5" />


                                        <Title order={5} my="xs">Done</Title>
                                        <Text>Paste the client id on the following <Text span fw="bold">iOS Client Id</Text> field.</Text>

                                    </ScrollArea>
                                </Paper>
                            </Tabs.Panel>
                        </Tabs>

                    </Grid.Col>
                </Grid>
                <Group justify="flex-end" mt="sm">
                    <Button type="submit" disabled={submitted} leftSection={submitted ? <Loader size="xs"/>: <IconServer/>} >Save</Button>
                </Group>
            </Box>
        </>
    )
}