import AppbarCustomization from "./AppbarCustomization";
import {
    ActionIcon,
    Box,
    Button,
    Divider,
    Flex,
    Group,
    Loader,
    LoadingOverlay, rem,
    Text,
    useMantineTheme
} from "@mantine/core";
import {IconAlertTriangle, IconCheck, IconServer, IconXboxX} from "@tabler/icons-react";
import NavbarCustomization from "./NavbarCustomization";
import DrawerCustomization from "./DrawerCustomization";
import ComponentCustomization from "./ComponentCustomization";
import {useDispatch, useSelector} from "react-redux";
import {setIsDirty, setSelectedComponent} from "../../../features/selectedComponent/selectedComponentSlice";
import {modals} from "@mantine/modals";
import {updateComponent} from "../../../features/pageComponents/componentsSlice";
import {updateActiveAppbar} from "../../../features/globalComponents/activeAppbarSlice";
import {updateActiveNavbar} from "../../../features/globalComponents/activeNavbarSlice";
import {updateActiveDrawer} from "../../../features/globalComponents/activeDrawerSlice";
import {useDisclosure} from "@mantine/hooks";
import {removeComponent, saveComponent} from "../../../features/pageComponents/componentsThunks";
import {notifications} from "@mantine/notifications";
import {saveAppbar, saveDrawer, saveNavbar} from "../../../features/globalComponents/globalComponentsThunks";
import {RESTRICTED_PAGES} from "../../../utils/constant";

const RightSidebar = () => {
    const theme = useMantineTheme();
    const dispatch = useDispatch();

    const { selectedComponent, copySelectedComponent, isDirty, loading } = useSelector((state) => state.selectedComponent);
    const { screenProperty } = useSelector((state) => state.components);
    const [saving, handlersSaving] = useDisclosure(false);
    const {viewMode} = useSelector(state => state.viewMode)




  if (null === selectedComponent) return false;

  if (RESTRICTED_PAGES.includes(screenProperty?.slug)) return false;


    const handleReset = () => {
        dispatch(setSelectedComponent(selectedComponent));

        if ('component' === selectedComponent?.mode){
            dispatch(updateComponent(selectedComponent));
        }else if ('appbar' === selectedComponent?.mode){
            dispatch(updateActiveAppbar(selectedComponent))
        }else if ('navbar' === selectedComponent?.mode){
            dispatch(updateActiveNavbar(selectedComponent))
        }else if ('drawer' === selectedComponent?.mode){
            dispatch(updateActiveDrawer(selectedComponent))
        }

        dispatch(setIsDirty(false));
    }
    const handelCloseEdit = () => {
        if (isDirty) {
            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 you want to discard them?
                        </Text>
                    </Flex>

                ),
                labels: {confirm: "Yes", cancel: "Continue Edit" },

                // 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: () => {
                    handleReset();
                    dispatch(setSelectedComponent(null))

                },
            });
        } else {
            dispatch(setSelectedComponent(null))
        }

    }

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

        let saveResponse = Promise.reject();
        if ('component' === copySelectedComponent?.mode){
            saveResponse =  dispatch(saveComponent(copySelectedComponent));
        }else if ('appbar' === copySelectedComponent?.mode){
            saveResponse = dispatch(saveAppbar(copySelectedComponent));
        }else if ('navbar' === copySelectedComponent?.mode){
            saveResponse = dispatch(saveNavbar(copySelectedComponent));
        }else if ('drawer' === copySelectedComponent?.mode){
            saveResponse = dispatch(saveDrawer(copySelectedComponent));
        }

        saveResponse
            .unwrap()
            .then(() => {
                dispatch(setIsDirty(false))
                notifications.show({
                    color: theme.primaryColor,
                    title: 'Data saved!',
                    icon: <IconCheck style={{width: rem(18), height: rem(18)}}/>,
                    loading: false,
                    autoClose: 2000,
                    withCloseButton: true,

                });
            })
            .catch((error) => console.error('Failed to save', error))
            .finally(() => handlersSaving.close());
    };


    const handleRemoveComponent = () => {

        modals.openConfirmModal({
            title: 'Are you sure?',
            centered: true,
            children: "",
            labels: {confirm: 'Yes', cancel: "No"},
            confirmProps: {color: theme.primaryColor},
            withCloseButton: false,
            overlayProps: {
                blur: 1,
            },
            closeOnClickOutside: false,
            onCancel: () => console.log('Cancel'),
            onConfirm: () => {
                dispatch(removeComponent(selectedComponent.id))
                    .unwrap()
                    .then(() => dispatch(setSelectedComponent(null)))
                    .catch((error) => console.log(error))
            }
        });
    }



    if ('preview' === viewMode) return false;

  return (

          <Box pt="sm" bg="white" mr={-1} pos="relative" h={`100vh`}>
              <LoadingOverlay
                  visible={loading}
                  zIndex={1000}
                  overlayProps={{ radius: "sm", blur: 5 }}
                  loaderProps={{ size: 'sm' }}
              />

              <Flex bg={`${theme.primaryColor}.0`} align="center" justify="space-between" p="xs">
                  <Text>
                      {selectedComponent?.name[0].toUpperCase() + selectedComponent?.name.slice(1).toLowerCase()}
                  </Text>
                  <ActionIcon
                      variant="light"
                      color={theme.colors.gray[5]}
                      onClick={handelCloseEdit}
                  >
                      <IconXboxX stroke={1.5} />
                  </ActionIcon>
              </Flex>
              <Box px="sm">

                  {"appbar" === selectedComponent?.mode && <AppbarCustomization/> }
                  {"navbar" === selectedComponent?.mode && <NavbarCustomization /> }
                  {"drawer" === selectedComponent?.mode && <DrawerCustomization/> }

                  {"component" === selectedComponent?.mode && <ComponentCustomization/> }

                  <Flex justify="space-between" align="center">
                      <Group>
                          <Button size="xs" variant="outline" onClick={handleReset} disabled={JSON.stringify(selectedComponent) === JSON.stringify(copySelectedComponent)}>Reset</Button>
                          {"component" === selectedComponent?.mode && <Button size="xs" variant="light" onClick={handleRemoveComponent}>Remove</Button>}
                      </Group>
                      <Button size="xs" leftSection={saving ? <Loader size="xs"/> : <IconServer/>} onClick={handleSave} disabled={saving}>Save</Button>
                  </Flex>

              </Box>
          </Box>
  );
};
export default RightSidebar;
