import React, { createContext, useContext, useState, useEffect } from "react";
import { ToastPosition, toast } from "react-toastify";
import CheckIcon from "../../../assets/images/check-icon.svg";
import ErrorIcon from "../../../assets/images/error-icon.svg";
import { useViewMode } from "./ViewModeContext";
import {
  SettingsContextProps,
  SettingsProviderProps,
} from "@app/models/components";
import { SfSyncSettings, ScopeOption } from "@app/models/global";
import { getHomeURLs, updateSfSyncSettings } from "@app/services/api";
import { useBlockNavigation } from "./NavigationContext";
import { LockIcon } from "@app/assets/images/icons";

const SettingsContext = createContext<SettingsContextProps>(
  {} as SettingsContextProps
);

export const SettingsProvider: React.FC<SettingsProviderProps> = ({
  children,
}) => {
  const [initialSettings, setInitialSettings] = useState<SfSyncSettings>(
    sfsyncData.settings
  );
  const [homeURLs, setHomeURLs] = useState<Record<string, string>>({});
  const [emptyConfigList, setEmptyConfigList] = useState(false);
  const [isSwitchingConfig, setIsSwitchingConfig] = useState(false);

  const { isRTL } = useViewMode();
  const { setIsNavBlocked, isNavBlocked } = useBlockNavigation();

  const defaultPosition = isRTL ? "top-left" : "top-right";

  const scopeOptions: ScopeOption[] = (
    sfsyncData.scopeOptions ?? [
      {
        text: "Post",
        value: "post",
      },
    ]
  ).map((option) => {
    return option;
  });

  useEffect(() => {
    const fetchHomeURLs = async () => {
      const urls = await getHomeURLs();

      if (urls.error) return;

      setHomeURLs(urls);
    };

    fetchHomeURLs();
  }, []);

  const showNotification = (
    type: "error" | "success",
    message: string,
    position: ToastPosition = defaultPosition,
    autoClose = 3000
  ) => {
    if (type === "error") {
      toast.error(message, {
        position,
        hideProgressBar: true,
        autoClose,
        icon: () => <img src={ErrorIcon} alt="Error Icon" />,
      });
    }

    if (type === "success") {
      toast.success(message, {
        position,
        hideProgressBar: true,
        autoClose,
        icon: () => <img src={CheckIcon} alt="Check Icon" />,
      });
    }
  };

  const handleChangeSelection = async (id: string) => {
    if (isNavBlocked || isSwitchingConfig) return;
    if (initialSettings.selected_config === id) return;

    setIsSwitchingConfig(true);
    setIsNavBlocked(true);

    const newSettings: SfSyncSettings = {
      ...initialSettings,
      selected_config: id,
    };

    setInitialSettings(newSettings);
    setIsSwitchingConfig(false);
    setIsNavBlocked(false);
  };

  useEffect(() => {
    const configList = initialSettings.config_list ?? {};
    setEmptyConfigList(!Object.keys(configList).length);
  }, [initialSettings]);

  return (
    <SettingsContext.Provider
      value={{
        initialSettings,
        showNotification,
        setInitialSettings,
        emptyConfigList,
        scopeOptions,
        isSwitchingConfig,
        handleChangeSelection,
        homeURLs,
      }}
    >
      {children}
    </SettingsContext.Provider>
  );
};

export const useSettings = () => {
  return useContext(SettingsContext);
};
