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 {
  DefaultRangeOption,
  CardElementStyles,
  SelectOption,
  SettingsContextProps,
  SettingsProviderProps,
  CardStyles,
} from "@app/models/components";
import { ScopeOption, TopPostsSettings } from "@app/models/global";
import { getHomeURLs } from "@app/services/api";
import { LockIcon } from "@app/assets/images/icons";

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

export const SettingsProvider: React.FC<SettingsProviderProps> = ({
  children,
}) => {
  const [initialSettings, setInitialSettings] = useState<TopPostsSettings>(
    topPostsData.settings
  );
  const [homeURLs, setHomeURLs] = useState<Record<string, string>>({});
  const { isRTL } = useViewMode();
  const defaultPosition = isRTL ? "top-left" : "top-right";
  const noConfig = !initialSettings.property_id;
  const { isPremium } = process.env.CONFIG;
  const localization = topPostsI18n.data;

  const cronjobOptions: SelectOption[] = [
    {
      text: localization.every_twelve_hours,
      value: "43200",
      icon: !isPremium ? LockIcon : null,
    },
    {
      text: localization.every_twenty_four_hours,
      value: "86400",
    },
  ];

  const createDateWithoutSeconds = (date: Date): Date => {
    const newDate = new Date(date);
    newDate.setSeconds(0, 0);
    return newDate;
  };

  const dateRangeOptions: DefaultRangeOption[] = [
    {
      title: localization.last_two_days,
      range: {
        from: createDateWithoutSeconds(
          new Date(Date.now() - 2 * 24 * 60 * 60 * 1000)
        ),
        to: createDateWithoutSeconds(new Date()),
      },
    },
    {
      title: localization.last_seven_days,
      range: {
        from: createDateWithoutSeconds(
          new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)
        ),
        to: createDateWithoutSeconds(new Date()),
      },
    },
    {
      title: localization.last_fourteen_days,
      range: {
        from: createDateWithoutSeconds(
          new Date(Date.now() - 14 * 24 * 60 * 60 * 1000)
        ),
        to: createDateWithoutSeconds(new Date()),
      },
    },
    {
      title: localization.last_thirty_days,
      range: {
        from: createDateWithoutSeconds(
          new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)
        ),
        to: createDateWithoutSeconds(new Date()),
      },
    },
    {
      title: localization.last_twelve_months,
      range: {
        from: createDateWithoutSeconds(
          new Date(Date.now() - 365 * 24 * 60 * 60 * 1000)
        ),
        to: createDateWithoutSeconds(new Date()),
      },
    },
  ];

  const scopeOptions: ScopeOption[] = (
    topPostsData.scopeOptions ?? [
      {
        text: localization.tag,
        value: "tag",
        icon: !isPremium ? LockIcon : null,
      },
      {
        text: localization.Post,
        value: "post",
      },
      {
        text: localization.category,
        value: "category",
        icon: !isPremium ? LockIcon : null,
      },
    ]
  ).map((option) => {
    if (option?.value !== "post") {
      return {
        ...option,
        icon: !isPremium ? LockIcon : null,
      };
    }
    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" />,
      });
    }
  };

  return (
    <SettingsContext.Provider
      value={{
        initialSettings,
        showNotification,
        setInitialSettings,
        noConfig,
        homeURLs,
        dateRangeOptions,
        scopeOptions,
        cronjobOptions,
      }}
    >
      {children}
    </SettingsContext.Provider>
  );
};

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