import Button from "@app/components/button/Button";
import CardContent from "@app/components/card-content/CardContent";
import CardFooter from "@app/components/card-footer/CardFooter";
import CardHeader from "@app/components/card-header/CardHeader";
import CardSection from "@app/components/card-section/CardSection";
import Card from "@app/components/card/Card";
import InputField from "@app/components/input-field/InputField";
import NumberInput from "@app/components/number-input/NumberInput";
import Select from "@app/components/select/Select";
import * as PopoverPrimitive from "@radix-ui/react-popover";
import {
  Analytics,
  UpdateFilterPayload,
  VerifyAPIKeyPayload,
} from "@app/models/api";
import {
  CardElementStyles,
  CardHeaderProps,
  CardStyles,
  Tag,
} from "@app/models/components";
import { TopPostsSettings } from "@app/models/global";
import {
  VerifyAPIKey,
  getFilters,
  updateFilter,
  updateTopPostsSettings,
} from "@app/services/api";
import { useSettings } from "@settings/contexts/SettingsContext";
import { useViewMode } from "@settings/contexts/ViewModeContext";
import React, { useEffect, useRef, useState } from "react";
import { Controller, ControllerRenderProps, useForm } from "react-hook-form";
import "./configuration-styles.scss";

import { cloneDeep, get, isEmpty, isEqual } from "lodash";
import Modal from "@app/components/modal/Modal";
import Radio from "@app/components/radio/Radio";
import ResultCard from "@app/components/result-card/ResultCard";
import CTACard from "@app/components/CTACard/CTACard";
import {
  BrushIcon,
  LockIcon,
  PointerIcon,
  ViewGrid2,
  ViewList,
  CheckCircleIcon,
  CancelIcon,
  ErrorIcon,
} from "@app/assets/images/icons";
import Tooltip from "@app/components/Tooltip/Tooltip";

import {
  cardDate,
  normalizeRangeForHeaders,
  getDataTypeOptions,
  getTaxonomiesOptions,
} from "@app/services/utilities";
import CustomizableCard from "@app/components/customizableCard/CustomizableCard";
import ColorPicker from "@app/components/color-picker/ColorPicker";
import {
  FontSizeOptions,
  TextStyleOptions,
  defaultElementStyling,
} from "@app/constants";
import InputGroup from "@app/components/input-group/InputGroup";
import EmptyState from "@app/components/EmptyState/EmptyState";

import UpgradePopover from "@app/components/UpgradePopover/UpgradePopover";
import {
  ActivePopover,
  useUpgradePopover,
} from "@settings/contexts/UpgradePopoverContext";

import Placeholder from "@app/assets/images/placeholder.jpg";
import Checkbox from "@app/components/checkbox/Checkbox";

const Configuration = () => {
  const { microSiteURL, isPremium } = process.env.CONFIG;
  const localization = topPostsI18n.data;
  const {
    initialSettings,
    setInitialSettings,
    showNotification,
    cronjobOptions,
  } = useSettings();

  const { activePopover, setActivePopover } = useUpgradePopover();

  const initialValues: TopPostsSettings = {
    api_key: "",
    api_key_verified: false,
    property_id: 0,
    scheduled_trigger: 86400,
    filters: {},
    site_id: topPostsData.site_id,
    results_style: "search_results_card",
    columns_number: 1,
    custom_styles: {},
    show_data_type: false,
    display_options: {
      post: {
        category: "category",
        tag: "post_tag",
        data_type: "post",
        post_name: topPostsData.languages.length > 0 ? {} : "",
      },
    },
  };

  const [settings, setSettings] = useState<TopPostsSettings>({
    ...initialValues,
    ...initialSettings,
  }); // we combine the initial values with the initial settings to get site_id
  const [isDeleting, setIsDeleting] = useState(false);
  const [isOpenDeleteConfigModal, setIsOpenDeleteConfigModal] = useState(false);
  const [isCustomStylesModalOpen, setIsCustomStylesModalOpen] = useState(false);
  const [selectedPostType, setSelectedPostType] = useState("post");
  const [analyticsData, setAnalyticsData] = useState<Array<Analytics>>([]);
  const [configHasChanges, setConfigHasChanges] = useState(false);
  const [displayOptionsHasChanges, setDisplayOptionsHasChanges] =
    useState(false);
  const [isOpenOptionsModal, setIsOpenOptionsModal] = useState(false);
  const [openPopover, setOpenPopover] = useState(-1);

  const [displayOptions, setDisplayOptions] = useState(
    !isEmpty(settings.display_options) ? settings.display_options : {}
  );

  const [showPostTypeInput, setShowPostTypeInput] = useState(false);
  const [showDataType, setShowDataType] = useState(
    settings?.show_data_type ?? false
  );

  const [postName, setPostName] = useState<any>(() => {
    const initialPostName =
      settings?.display_options?.[selectedPostType]?.post_name;

    return initialPostName !== undefined
      ? initialPostName
      : topPostsData?.languages.length > 0
      ? {}
      : selectedPostType;
  });

  const { isRTL } = useViewMode();

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

  const [isStoring, setIsStoring] = useState(false);
  const [showConfigSections, setShowConfigSections] = useState(
    initialSettings.api_key_verified
  );
  const [isVerifyingAPIKey, setIsVerifyingAPIKey] = useState(false);
  const [showCheck, setShowCheck] = useState(false);
  const [currentElement, setCurrentElement] = useState("");
  const [ApiKey, setApiKey] = useState<string>(settings.api_key ?? "");
  const [verifyResult, setVerifyResult] = useState(false);
  const [changeVerifyState, setChangeVerifyState] = useState(
    initialSettings.api_key == "" ? true : false
  );
  const [concealedKey, setConcealedKey] = useState(concealKey(ApiKey));

  function concealKey(key: string) {
    if (!key) {
      return "";
    }
    let starCount = key.length;

    let starsString = key.slice(0, 5) + "*".repeat(starCount - 5);

    return starsString;
  }

  const handleVerifyAPI = async () => {
    setIsVerifyingAPIKey(true);

    const verifyAPIKeyPayload: VerifyAPIKeyPayload = {
      site_id: topPostsData.site_id,
    };

    const verifyAPIKeyResp = await VerifyAPIKey(ApiKey, verifyAPIKeyPayload);

    if (verifyAPIKeyResp?.error) {
      setIsVerifyingAPIKey(false);
      setVerifyResult(true); //show the check mark after receiving the response.
      setShowCheck(false);
      setShowConfigSections(false);
      setInitialSettings(initialValues);
      setSettings(initialValues);
      return;
    }

    let getFiltersResp = await getFilters(ApiKey, topPostsData.site_id);

    if (getFiltersResp?.error) {
      setIsStoring(false);
      const errorMessage = localization.saving_settings_error;
      showNotification(
        "error",
        `${errorMessage} (${localization.error} ${getFiltersResp?.status})`,
        toastPosition
      );
      return;
    }

    const filters = getFiltersResp.filters;
    const filterKeys = Object.keys(filters || {});

    if (filterKeys.length == 0) {
      const filterData = {
        display_name: localization.myFilter,
        description:
          localization.this_is_a_description_of_this_filter_please_edit_me,
        limit: !isPremium ? 5 : 500,
        scheduled_trigger: 86400,
        language: topPostsData.defaultLanguage,
        date_range: 604800,
        page: {},
        pinned: [],
        excluded: [],
      };

      const payload: UpdateFilterPayload = {
        site_id: topPostsData.site_id,
        filter_data: filterData,
      };

      const updateFilterResp = await updateFilter(ApiKey, payload);

      if (updateFilterResp?.error) {
        setIsStoring(false);
        const errorMessage = localization.saving_settings_error;
        showNotification(
          "error",
          `${errorMessage} (${localization.error} ${updateFilterResp?.status})`,
          toastPosition
        );
        return;
      }

      getFiltersResp = await getFilters(ApiKey, topPostsData.site_id);

      //second call
      if (isEmpty(getFiltersResp.filters)) {
        getFiltersResp = await getFilters(ApiKey, topPostsData.site_id);

        if (getFiltersResp?.error) {
          setIsStoring(false);
          const errorMessage = localization.saving_settings_error;
          showNotification(
            "error",
            `${errorMessage} (${localization.error} ${getFiltersResp?.status})`,

            toastPosition
          );
          return;
        }
      }
    }
    const updatedSettings = {
      ...settings,
      property_id: Number(verifyAPIKeyResp.data.property_id),
      filters: getFiltersResp.filters,
      api_key_verified: true,
      api_key: ApiKey,
    };

    const isSettingsChanged = isEqual(initialSettings, updatedSettings);

    if (!isSettingsChanged) {
      const updateSettingsResp = await updateTopPostsSettings(updatedSettings);
      if (updateSettingsResp?.error) {
        let errorMessage =
          updateSettingsResp?.status === 400
            ? updateSettingsResp?.message
            : `${localization.saving_settings_error} (${localization.error} ${updateSettingsResp?.status})`;
        //step #1
        showNotification("error", errorMessage, toastPosition);
        setIsVerifyingAPIKey(false);
        return;
      }

      setSettings((prevVal) => ({
        ...prevVal,

        custom_styles: updateSettingsResp.updatedSettings.custom_styles, // Sometimes the custom_styles object is empty and an array is returned by PHP
        filters: updateSettingsResp.updatedSettings.filters,
      }));

      setInitialSettings(updateSettingsResp.updatedSettings);
    }

    setShowConfigSections(true);
    setShowCheck(true);
    setIsVerifyingAPIKey(false);
    setVerifyResult(true);
    setSettings((prev) => ({
      ...prev,
      property_id: Number(verifyAPIKeyResp.data.property_id),
      api_key_verified: true,
      api_key: ApiKey,
    }));
    setChangeVerifyState(false);
  };

  const previewCardTags = [
    {
      label: localization.tag_1,
      href: "#",
    },
    {
      label: localization.tag_2,
      href: "#",
    },
  ];

  const {
    control,
    handleSubmit,
    formState: { errors },
    reset,
  } = useForm<TopPostsSettings>({
    defaultValues: {
      ...initialValues,
      ...initialSettings,
    },
    mode: "all",
  });

  const headerProps: CardHeaderProps = {
    title: localization.plugin_settings,
    subtitle: <>{localization.plugin_subtitle}</>,
  };

  const [currentStyles, setCurrentStyles] = useState<CardStyles>(
    isEmpty(settings?.custom_styles)
      ? defaultElementStyling
      : settings?.custom_styles
  );
  const onClearTaxonomies = (taxonomies: [string]) => {
    taxonomies.forEach((name) => {
      updateTaxonomyConfig(name, "");
    });
  };

  const paddingProperties = [
    {
      label: localization.top,
      name: localization.padding_top,
      placeholder: localization.padding_top_placeholder,
    },
    {
      label: localization.right,
      name: localization.padding_right,
      placeholder: localization.padding_right_placeholder,
    },
    {
      label: localization.bottom,
      name: localization.padding_bottom,
      placeholder: localization.padding_bottom_placeholder,
    },
    {
      label: localization.left,
      name: localization.padding_left,
      placeholder: localization.padding_left_placeholder,
    },
  ];

  const popoverContent = (
    <>
      <p className="configuration-popoverContentTitle">
        <b>{localization.top_posts_for_google_analytics}</b>
      </p>
      <Button
        id="configuration-popoverContentButton"
        text={localization.upgrade_to_premium}
        onClickHandler={() => {
          window.open(
            `${microSiteURL}/dashboard#add-site?site_id=${topPostsData.site_id}&action=upgrade`,
            "_blank"
          );
        }}
      />
      <PopoverPrimitive.Arrow className="PopoverArrow" />
    </>
  );

  const FreqPopoverRef = useRef<HTMLDivElement>(null);
  const FancyPopoverRef = useRef<HTMLDivElement>(null);
  const CustomizablePopoverRef = useRef<HTMLDivElement>(null);
  const NoDefaultLangPopoverRef = useRef<HTMLDivElement>(null);
  const DisplayOptionsPopoverRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const mainRefs = [
        FreqPopoverRef,
        FancyPopoverRef,
        CustomizablePopoverRef,
        DisplayOptionsPopoverRef,
      ];

      // Handle click outside logic for main popovers
      const isClickOutsideMain = mainRefs.every(
        (ref) => ref.current && !ref.current.contains(event.target as Node)
      );

      // Handle click outside logic for the modal popover
      const isClickOutsideModal =
        NoDefaultLangPopoverRef.current &&
        !NoDefaultLangPopoverRef.current.contains(event.target as Node);

      // Close popovers only if the click is outside both main popovers and the modal popover
      if (isClickOutsideMain && isClickOutsideModal) {
        setActivePopover(ActivePopover.None);
        setOpenPopover(-1);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [
    setActivePopover,
    FreqPopoverRef,
    FancyPopoverRef,
    CustomizablePopoverRef,
    DisplayOptionsPopoverRef,
    NoDefaultLangPopoverRef,
  ]);

  useEffect(() => {
    const configHasChanges = !isEqual(initialSettings, settings);
    setConfigHasChanges(configHasChanges);
  }, [initialSettings, settings]);

  useEffect(() => {
    const displayOptionsHasChanges =
      !isEqual(displayOptions, settings.display_options) ||
      showDataType !== settings.show_data_type;

    setDisplayOptionsHasChanges(displayOptionsHasChanges);
  }, [displayOptions, settings, showDataType]);

  useEffect(() => {
    if (isEmpty(displayOptions[selectedPostType])) {
      setDisplayOptions((prevDisplayOptions) => ({
        ...prevDisplayOptions,
        [selectedPostType]: {},
      }));
    }
  }, [selectedPostType]);

  const generateCustomizableCard = (isCustomizable: boolean) => {
    const onElementClickHandler = isCustomizable
      ? handleElementClick
      : undefined;

    return (
      <CustomizableCard
        title={localization.this_is_a_customizable_card}
        body={localization.customize_styles_subtitle}
        date={cardDate}
        tags={(renderPostType("tag") as Tag[]) ?? previewCardTags}
        href="#"
        image={Placeholder}
        category={
          (renderPostType("category") as string) ?? localization.category
        }
        type={
          showDataType
            ? (renderPostType("data_type") as string) ?? localization.type
            : ""
        }
        styling={isCustomizable ? currentStyles : settings.custom_styles}
        isCustomizable={isCustomizable}
        onElementClickHandler={onElementClickHandler}
      />
    );
  };
  const generateFancyCard = () => {
    return (
      <CTACard
        title={localization.this_is_a_fancy_card}
        tag={(renderPostType("category") as string) ?? localization.category}
        meta={cardDate}
        imageSrc={Placeholder}
        type={
          showDataType
            ? (renderPostType("data_type") as string) ?? localization.type
            : ""
        }
      />
    );
  };

  const generateSearchResultsCard = () => {
    return (
      <ResultCard
        title={localization.this_is_a_search_results_card}
        body={localization.search_results_subtitle}
        date={cardDate}
        tags={(renderPostType("tag") as Tag[]) ?? previewCardTags}
        href="#"
        image={Placeholder}
        category={
          (renderPostType("category") as string) ?? localization.category
        }
        type={
          showDataType
            ? (renderPostType("data_type") as string) ?? localization.type
            : ""
        }
      />
    );
  };

  const postNameValue: any =
    typeof displayOptions?.[selectedPostType]?.post_name === "object"
      ? ""
      : postName || "";

  const postNameObject = (langCode: string) => {
    return typeof settings?.display_options?.[selectedPostType]?.post_name ===
      "string"
      ? postName?.[langCode]
      : postName?.[langCode] ?? "";
  };

  let postNameObjectString: string;

  // Check if post_name is a string or an object
  if (
    typeof settings?.display_options?.[selectedPostType]?.post_name === "string"
  ) {
    // If post_name is a string, treat it as a string object with language keys
    const postName = displayOptions?.[selectedPostType]?.post_name as {
      [key: string]: string;
    };
    postNameObjectString = postName?.[topPostsData.defaultLanguage];
  } else {
    // If post_name is an object, access the language key or default to selectedPostType
    const postName = displayOptions?.[selectedPostType]?.post_name as
      | { [key: string]: string }
      | undefined;
    postNameObjectString =
      postName?.[topPostsData.defaultLanguage] ?? selectedPostType;
  }

  const renderPostType = (taxonomy: string) => {
    const postData = displayOptions?.[selectedPostType];

    if (!postData) {
      return;
    }
    const { category, tag, data_type } = postData;
    if (taxonomy === "category") {
      return category ? category : localization.category;
    } else if (taxonomy === "tag") {
      return tag ? [{ label: tag, href: "#" }] : previewCardTags;
    } else if (taxonomy === "data_type") {
      // Check if data_type matches selectedPostType and render postName if true
      if (data_type === selectedPostType) {
        if (topPostsData.languages.length > 0) {
          return postNameObjectString;
        } else {
          return postNameValue;
        }
      } else {
        // Return a default value or handle the case where data_type is undefined
        return data_type ? data_type : localization.type;
      }
    }
  };

  const updateConfig = (name: string, value: any) => {
    if (name === "results_style" && !isPremium && value == "fancy_card") {
      setActivePopover(ActivePopover.FancyCard);

      return;
    }
    if (
      name === "results_style" &&
      !isPremium &&
      value == "customizable_card"
    ) {
      setActivePopover(ActivePopover.CustomizableCard);
      return;
    }
    setSettings((prevConfig) => ({
      ...prevConfig,
      [name]: value,
    }));
  };

  const updatePostTypeConfig = (name: string, value: string) => {
    if (!isPremium && value != "post") {
      setActivePopover(ActivePopover.DisplayOptions);
      return;
    }
    setSelectedPostType(value);
  };

  const updateTaxonomyConfig = (name: string, value: any) => {
    setDisplayOptions((prevSettings) => {
      // Create a deep copy of the state
      const updatedOptions = cloneDeep(prevSettings);

      if (
        !updatedOptions[selectedPostType] ||
        typeof updatedOptions[selectedPostType] !== "object"
      ) {
        updatedOptions[selectedPostType] = {};
      }

      // If data_type is not equal to selectedPostType, remove post_name
      if (name === "data_type" && value !== selectedPostType) {
        delete updatedOptions[selectedPostType].post_name;

        setShowPostTypeInput(false);
      }

      if (value === "") {
        // Remove the property if the value is an empty string
        delete (updatedOptions[selectedPostType] as Record<string, any>)[name];
      } else {
        (updatedOptions[selectedPostType] as Record<string, any>)[name] = value;
        if (Object.keys(updatedOptions[selectedPostType]).length === 0) {
          updatedOptions[selectedPostType] = {}; // Ensure it's an empty object
        }
      }

      return updatedOptions;
    });
  };

  const handleSavePostOptions = () => {
    if (displayOptions[selectedPostType]?.data_type != selectedPostType) {
      if (topPostsData.languages.length > 0) {
        setPostName({});
      } else {
        setPostName(selectedPostType);
      }
    }
    setSettings((prevSettings) => ({
      ...prevSettings,
      display_options: {
        ...displayOptions,
      },
      show_data_type: showDataType,
    }));
    setShowPostTypeInput(false);
    setIsOpenOptionsModal(false);
  };

  const handleNumberInputChange = (
    name: string,
    value: string | number | null
  ) => {
    if (name == "scheduled_trigger" && !isPremium && value != 86400) {
      setActivePopover(ActivePopover.Frequency);
      return;
    } else {
      updateConfig(name, Number(value));
    }
  };

  const handlePostName = (name: string, value: string, language: string) => {
    const filteredPostName = Object.keys(postName)
      .filter((key) => isNaN(Number(key))) // Remove numeric keys
      .reduce(
        (obj, key) => {
          obj[key] = postName[key];
          return obj;
        },
        {} as { [key: string]: string }
      );

    // Set the new state with the filtered postName and the new key-value pair
    setPostName({ ...filteredPostName, [language]: value });
    setDisplayOptions((prevSettings) => {
      const updatedOptions: any = cloneDeep(prevSettings);

      if (!updatedOptions[selectedPostType]) {
        updatedOptions[selectedPostType] = {};
      }

      if (
        !updatedOptions[selectedPostType][name] ||
        typeof updatedOptions[selectedPostType][name] !== "object"
      ) {
        updatedOptions[selectedPostType][name] = {}; // Initialize as object if not exists
      }
      if (value === "") {
        delete updatedOptions[selectedPostType][name][language];
      } else {
        // Add or update language value
        updatedOptions[selectedPostType][name][language] = value;
      }

      return updatedOptions;
    });
  };

  const handleDefaultPostName = (name: string, value: string) => {
    setPostName(value);
    setDisplayOptions((prevSettings) => {
      const updatedOptions: any = cloneDeep(prevSettings);

      if (value === "") {
        delete updatedOptions[selectedPostType][name];
      } else {
        updatedOptions[selectedPostType][name] = value;
      }

      return updatedOptions;
    });
  };

  const handleCloseOptionsModal = () => {
    setDisplayOptions(settings.display_options);
    setIsOpenOptionsModal(false);
    reset();
  };
  const discardChanges = () => {
    setSettings(initialSettings);
  };

  const handleNumberFieldChange = (
    value: string | number | null,
    field: ControllerRenderProps<TopPostsSettings, any>
  ) => {
    field.onChange(value);

    handleNumberInputChange(field.name, value);
  };

  const handleFormSubmit = async () => {
    if (!initialSettings.site_id) {
      return;
    }

    setIsStoring(true);

    const updatedSettingsResp = await updateTopPostsSettings(settings);

    const updatedSettings =
      updatedSettingsResp.updatedSettings as TopPostsSettings;

    setSettings((prevVal) => ({
      ...prevVal,

      custom_styles: updatedSettings.custom_styles, // Sometimes the custom_styles object is empty and an array is returned by PHP
      filters: updatedSettings.filters,
    }));

    setInitialSettings(updatedSettings);
    setIsStoring(false);
    showNotification(
      "success",
      localization.configuration_updated,
      toastPosition
    );
  };

  const handleDeleteConfig = async () => {
    setIsDeleting(true);

    const updateSettingsResp = await updateTopPostsSettings(initialValues);

    if (updateSettingsResp?.error) {
      setIsDeleting(false);
      showNotification(
        "error",
        `${localization.failed_delete_configuration_error} (${localization.error} ${updateSettingsResp?.error})`,
        toastPosition
      );

      return;
    }
    setCurrentStyles(defaultElementStyling);
    setDisplayOptions(initialValues.display_options);
    setIsDeleting(false);
    if (topPostsData.languages.length > 0) {
      setPostName({});
    } else {
      setPostName("");
    }
    setIsOpenDeleteConfigModal(false);
    setShowConfigSections(false);
    setApiKey("");
    setConcealedKey("");
    setInitialSettings(initialValues);
    setSettings(initialValues);
    setVerifyResult(false);
    setChangeVerifyState(true);
  };

  const handleElementClick = (elementName: string) => {
    setCurrentElement(elementName);
  };

  const handleSaveStyle = () => {
    if (currentElement) {
      setCurrentElement("");
      setSettings({ ...settings, custom_styles: currentStyles });

      setIsCustomStylesModalOpen(false);
    }
  };

  const handleCloseModal = () => {
    setCurrentElement("");
    setCurrentStyles(settings.custom_styles);
    setIsCustomStylesModalOpen(false);
  };

  const handleStyleChange = (name: string, value: string | number | null) => {
    if (currentElement) {
      setCurrentStyles((prevStyles) => ({
        ...prevStyles,
        [currentElement]: {
          ...prevStyles[currentElement],
          [name]: value,
        },
      }));
    }
  };

  const convertPixelsToNumber = (value: string | undefined): string => {
    if (!value) return "";
    return value.replace("px", "");
  };

  const configSectionProps = {
    "api-key-verification": {
      key: "api-key-verification",
      sectionID: "api-key-verification",
      sectionTitle: localization.api_key,
      sectionSubtitle: localization.api_key_subtitle,
    },
    ...(showConfigSections && {
      "google-analytics-integration": {
        key: "google-analytics-integration",
        sectionID: "google-analytics-integration",
        sectionTitle: localization.google_analytics_integration,
        sectionSubtitle: localization.google_analytics_subtitle,
      },
      "display-options-per-data-type": {
        key: "display-options-per-data-type",
        sectionID: "display-options-per-data-type",
        sectionTitle: localization.display_options_per_data_type,
        sectionSubtitle: localization.display_options_subtitle,
      },
      "displayed-results-style": {
        key: "displayed-results-style",
        sectionID: "displayed-results-style",
        sectionTitle: localization.display_results_style,
        sectionSubtitle: localization.display_results_subtitle,
      },
    }),
  };

  const getColumnSwitcherButtons = () => (
    <div className="configuration-columnsNumberPicker">
      {settings.results_style == "customizable_card" && (
        <>
          <Tooltip text={localization.custom_css_styles} gap={4}>
            <Button
              icon={BrushIcon}
              variant="tertiary"
              onClickHandler={() => {
                setIsCustomStylesModalOpen(true);
              }}
              collapse
            />
          </Tooltip>
          <span className="configuration-IconSeparator"></span>
        </>
      )}
      <Tooltip text={localization.single_column_layout} gap={4}>
        <Button
          icon={ViewList}
          variant={settings.columns_number === 1 ? "ghost" : "tertiary"}
          style={{
            pointerEvents: `${settings.columns_number === 1 ? "none" : "auto"}`,
          }}
          onClickHandler={() => updateConfig("columns_number", 1)}
          collapse
        />
      </Tooltip>
      <Tooltip text={localization.two_column_layout} gap={4}>
        <Button
          icon={ViewGrid2}
          variant={settings.columns_number === 2 ? "ghost" : "tertiary"}
          style={{
            pointerEvents: `${settings.columns_number === 2 ? "none" : "auto"}`,
          }}
          onClickHandler={() => updateConfig("columns_number", 2)}
          collapse
        />
      </Tooltip>
    </div>
  );

  const configSectionContent: { [key: string]: any[] } = {
    "api-key-verification": [
      <div className="configuration-api-key-container">
        {" "}
        <div className="configuration-api-key">
          <div className="configuration-api-key-verification">
            {" "}
            <InputField
              containerID="configuration-api-key-input"
              name="api-key"
              value={concealedKey}
              onChange={(name, value) => {
                setConcealedKey(concealKey(value));
                setApiKey(value);
                setVerifyResult(false);
              }}
              disabled={
                initialSettings.api_key !== undefined &&
                initialSettings.api_key !== "" &&
                !changeVerifyState
              }
            />
            {!changeVerifyState &&
              initialSettings.api_key !== undefined &&
              initialSettings.api_key.trim() !== "" && (
                <div className="configuration-checkIcon">{CheckCircleIcon}</div>
              )}
            {verifyResult && !showCheck && (
              <div className="configuration-checkIcon">{CancelIcon}</div>
            )}
          </div>

          <div className="configuration-buttonIcon-container">
            {changeVerifyState || initialSettings.api_key == undefined ? (
              <Button
                text={localization.verify}
                onClickHandler={handleVerifyAPI}
                id="configuration-verifyButton"
                variant="ghost"
                isLoading={isVerifyingAPIKey}
                disabled={concealedKey === "" || isVerifyingAPIKey}
              />
            ) : (
              <Button
                text={localization.change}
                id="configuration-verifyButton"
                variant="ghost"
                onClickHandler={() => {
                  setChangeVerifyState(true);
                  setVerifyResult(false);
                  setConcealedKey("");
                }}
              />
            )}
          </div>
        </div>
        <a
          href={`${microSiteURL}/dashboard#add-site?site_id=${topPostsData.site_id}`}
          target="_blank"
          rel="noopener noreferrer"
          className="configuration-api-key-link"
        >
          {localization.get_api_key_link}
        </a>
      </div>,
    ],
    "google-analytics-integration": [
      <InputField
        label={localization.property_id}
        type="text"
        placeholder={localization.property_id_placeholder}
        value={settings.property_id ?? 0}
        onChange={(name, value) => {}}
        description={
          <>
            localization.get_your_property_id{" "}
            <a href="#">{localization.this_link}</a>.
          </>
        }
        disabled
      />,
      !isPremium ? (
        <div ref={FreqPopoverRef} className="configuration-popoverButton">
          <UpgradePopover
            open={activePopover === ActivePopover.Frequency}
            onOpenChange={() => setActivePopover(ActivePopover.None)}
            content={
              <div className="configuration-Selector-popoverContent">
                {popoverContent}
              </div>
            }
          >
            <Select
              key="scheduled_trigger"
              id="scheduled_trigger"
              name="scheduled_trigger"
              value={
                settings.scheduled_trigger
                  ? settings.scheduled_trigger.toString()
                  : null
              }
              label={localization.frequency}
              onChange={handleNumberInputChange}
              placeholder={localization.frequency_placeholder}
              options={cronjobOptions}
              defaultValue="86400"
            />
          </UpgradePopover>
        </div>
      ) : (
        <Select
          key="scheduled_trigger"
          id="scheduled_trigger"
          name="scheduled_trigger"
          value={
            settings.scheduled_trigger
              ? settings.scheduled_trigger.toString()
              : null
          }
          label={localization.frequency}
          onChange={handleNumberInputChange}
          placeholder={localization.frequency_placeholder}
          options={cronjobOptions}
          defaultValue="86400"
        />
      ),
    ],

    "display-options-per-data-type": [
      <div className="configuration-postType">
        {!isPremium ? (
          <div
            className="configuration-postTypeSelect  configuration-popoverButton"
            ref={DisplayOptionsPopoverRef}
          >
            <UpgradePopover
              open={activePopover === ActivePopover.DisplayOptions}
              content={
                <div className="configuration-Selector-popoverContent">
                  {popoverContent}
                </div>
              }
            >
              <Select
                key="post_type"
                id="post_type"
                name="post_type"
                value={selectedPostType}
                label={localization.post_type}
                onChange={updatePostTypeConfig}
                placeholder={localization.select_post_type_placeholder}
                options={getDataTypeOptions(
                  topPostsData.dataTypeDisplayOptions
                )}
                defaultValue={localization.post}
              />
            </UpgradePopover>
          </div>
        ) : (
          <div className="configuration-postTypeSelect">
            <Select
              key="post_type"
              id="post_type"
              name="post_type"
              value={selectedPostType}
              label={localization.post_type}
              onChange={updatePostTypeConfig}
              placeholder={localization.select_post_type_placeholder}
              options={getDataTypeOptions(topPostsData.dataTypeDisplayOptions)}
              defaultValue={localization.post}
            />
          </div>
        )}
        <Button
          onClickHandler={() => setIsOpenOptionsModal(true)}
          text={localization.change_display_options}
          id="configuration-displayOptionsButton"
          variant="ghost"
        />
      </div>,
    ],
    "displayed-results-style": [
      <div
        key="displayed-results-style-1"
        className="configuration-resultStyleWrapper"
      >
        <div className="configuration-resultStyleRadio">
          <Radio
            name="results_style"
            containerID="configuration-resultStyle--search"
            value="search_results_card"
            label={localization.search_result_card}
            onChange={(e) => updateConfig("results_style", e.target.value)}
            checked={settings.results_style === "search_results_card"}
          />
          {settings.results_style === "search_results_card" &&
            getColumnSwitcherButtons()}
        </div>
        <div className="configuration-resultStylePreview">
          <div
            className="configuration-resultStylePreview--overlay"
            onClick={() => updateConfig("results_style", "search_results_card")}
          ></div>
          {generateSearchResultsCard()}
        </div>
      </div>,
      !isPremium ? (
        <div
          key="displayed-results-style-2"
          ref={FancyPopoverRef}
          className="configuration-popoverButton"
        >
          <UpgradePopover
            open={activePopover === ActivePopover.FancyCard}
            content={
              <div className="configuration-FancyCard-popoverContent">
                {popoverContent}
              </div>
            }
          >
            <div className="configuration-resultStyleWrapper">
              <div className="configuration-resultStyleRadio">
                <Radio
                  name="results_style"
                  containerID="configuration-resultStyle--fancy"
                  value="fancy_card"
                  label={localization.fancy_card}
                  onChange={(e) =>
                    updateConfig("results_style", e.target.value)
                  }
                  checked={settings.results_style === "fancy_card"}
                  rightIcon={!isPremium ? LockIcon : null}
                />
                {settings.results_style === "fancy_card" &&
                  getColumnSwitcherButtons()}
              </div>
            </div>
          </UpgradePopover>
          <div className="configuration-resultStyleWrapper">
            <div className="configuration-resultStylePreview">
              <div
                className="configuration-resultStylePreview--overlay"
                onClick={() => updateConfig("results_style", "fancy_card")}
              ></div>
              {generateFancyCard()}
            </div>
          </div>
        </div>
      ) : (
        <div
          key="displayed-results-style-2"
          className="configuration-resultStyleWrapper"
        >
          <div className="configuration-resultStyleRadio">
            <Radio
              name="results_style"
              containerID="configuration-resultStyle--fancy"
              value="fancy_card"
              label={localization.fancy_card}
              onChange={(e) => updateConfig("results_style", e.target.value)}
              checked={settings.results_style === "fancy_card"}
              rightIcon={!isPremium ? LockIcon : null}
            />
            {settings.results_style === "fancy_card" &&
              getColumnSwitcherButtons()}
          </div>
          <div className="configuration-resultStylePreview">
            <div
              className="configuration-resultStylePreview--overlay"
              onClick={() => updateConfig("results_style", "fancy_card")}
            ></div>
            {generateFancyCard()}
          </div>
        </div>
      ),
      !isPremium ? (
        <div
          key="displayed-results-style-3"
          ref={CustomizablePopoverRef}
          className="configuration-popoverButton"
        >
          <UpgradePopover
            open={activePopover === ActivePopover.CustomizableCard}
            content={
              <div className="configuration-CustomizableCard-popoverContent">
                {popoverContent}
              </div>
            }
          >
            <div className="configuration-resultStyleWrapper">
              <div className="configuration-resultStyleRadio">
                <Radio
                  name="results_style"
                  containerID="configuration-resultStyle--customize"
                  value="customizable_card"
                  label={localization.customizable_card}
                  onChange={(e) =>
                    updateConfig("results_style", e.target.value)
                  }
                  checked={settings.results_style === "customizable_card"}
                  rightIcon={!isPremium ? LockIcon : null}
                />

                {settings.results_style === "customizable_card" &&
                  getColumnSwitcherButtons()}
              </div>
            </div>
          </UpgradePopover>
          <div className="configuration-resultStyleWrapper">
            <div className="configuration-resultStylePreview">
              <div
                className="configuration-resultStylePreview--overlay"
                onClick={() =>
                  updateConfig("results_style", "customizable_card")
                }
              ></div>
              {generateCustomizableCard(false)}
            </div>
          </div>
        </div>
      ) : (
        <div
          key="displayed-results-style-3"
          className="configuration-resultStyleWrapper"
        >
          <div className="configuration-resultStyleRadio">
            <Radio
              name="results_style"
              containerID="configuration-resultStyle--customize"
              value="customizable_card"
              label={localization.customizable_card}
              onChange={(e) => updateConfig("results_style", e.target.value)}
              checked={settings.results_style === "customizable_card"}
              rightIcon={!isPremium ? LockIcon : null}
            />
            {settings.results_style === "customizable_card" &&
              getColumnSwitcherButtons()}
          </div>
          <div className="configuration-resultStylePreview">
            <div
              className="configuration-resultStylePreview--overlay"
              onClick={() => updateConfig("results_style", "customizable_card")}
            ></div>
            {generateCustomizableCard(false)}
          </div>
        </div>
      ),
    ],
  };

  return (
    <div className="settings-wrapper configuration">
      <Card>
        <CardHeader {...headerProps} />
        <form onSubmit={handleSubmit(handleFormSubmit)}>
          <CardContent>
            {Object.keys(configSectionProps).map((key: string) => (
              <CardSection
                {...configSectionProps[key as keyof typeof configSectionProps]}
              >
                {configSectionContent[key]}
              </CardSection>
            ))}
          </CardContent>
          {showConfigSections && (
            <CardFooter>
              <Button
                disabled={!configHasChanges || isStoring || isDeleting}
                type="submit"
                text={isStoring ? localization.saving : localization.save}
                isLoading={isStoring}
              />
              <Button
                text={localization.discard}
                variant="secondary"
                onClickHandler={discardChanges}
                disabled={!configHasChanges || isStoring || isDeleting}
              />
              {initialSettings.property_id !== 0 && (
                <Button
                  isDestructive
                  text={
                    isDeleting
                      ? localization.resetting_plugin
                      : localization.reset_plugin
                  }
                  variant="tertiary"
                  onClickHandler={() => setIsOpenDeleteConfigModal(true)}
                  disabled={
                    isStoring || isDeleting || initialSettings.property_id == 0
                  }
                />
              )}
            </CardFooter>
          )}
        </form>
      </Card>

      <Modal
        isOpen={isOpenDeleteConfigModal}
        onClose={() => setIsOpenDeleteConfigModal(false)}
        title={localization.reset_plugin}
        modalActions={[
          {
            text: localization.reset,
            type: "button",
            isDestructive: true,
            isLoading: isDeleting,
            onClickHandler: handleDeleteConfig,
          },
          {
            text: localization.cancel,
            variant: "secondary",
            type: "button",
            onClickHandler: () => setIsOpenDeleteConfigModal(false),
          },
        ]}
      >
        <p className="manager-modalDescription">
          {localization.reset_plugin_modal}
        </p>
      </Modal>
      <Modal
        isOpen={isCustomStylesModalOpen}
        onClose={handleCloseModal}
        title={`${localization.customize} ${currentElement}`}
        maxWidth="600px"
        modalActions={[
          {
            text: localization.save,
            type: "button",
            disabled: currentElement == "",
            onClickHandler: handleSaveStyle,
          },
          {
            text: localization.cancel,
            variant: "secondary",
            type: "button",
            onClickHandler: handleCloseModal,
          },
        ]}
      >
        <>
          <div className="configuration-customizableCard-description-container">
            <p className="configuration-modalDescription">
              {localization.customize_card_modal}
            </p>
            <div className="configuration-customizableCardContainer">
              {generateCustomizableCard(true)}
            </div>
          </div>
          {currentElement == "" ? (
            <div className="configuration-emptyState">
              <EmptyState
                icon={PointerIcon}
                title={localization.select_an_element}
                subtitle={localization.customize_element_subtitle}
              />
            </div>
          ) : (
            <>
              <Select
                key="fontStyle"
                id="fontStyle"
                name="fontStyle"
                label={localization.font_style}
                value={currentStyles?.[currentElement]?.fontStyle || ""}
                onChange={handleStyleChange}
                options={TextStyleOptions}
                defaultValue={localization.normal}
              />
              <Select
                key="fontSize"
                id="fontSize"
                name="fontSize"
                label={localization.font_size}
                value={currentStyles?.[currentElement]?.fontSize || ""}
                onChange={handleStyleChange}
                options={FontSizeOptions}
                defaultValue={localization.medium}
              />
              <NumberInput
                name="lineHeight"
                label={localization.line_height}
                value={currentStyles?.[currentElement]?.lineHeight}
                min={0}
                max={5}
                placeholder={localization.line_height_placeholder}
                onChange={(name, value) => {
                  handleStyleChange(name, value);
                }}
              />
              <div className="flex-row-center gap-12">
                <ColorPicker
                  name="color"
                  value={currentStyles?.[currentElement]?.color}
                  onChange={handleStyleChange}
                  label={localization.text_color}
                  placeholder={localization.text_color_placeholder}
                />
                <ColorPicker
                  name="backgroundColor"
                  value={currentStyles?.[currentElement]?.backgroundColor}
                  onChange={handleStyleChange}
                  label={localization.background_color}
                  placeholder={localization.bg_color_placeholder}
                />
              </div>

              <div className="configuration-CustomStyle-padding">
                <InputGroup groupTitle="Padding">
                  {paddingProperties.map(({ label, name, placeholder }) => (
                    <NumberInput
                      key={name}
                      name={name}
                      label={label}
                      value={convertPixelsToNumber(
                        currentStyles?.[currentElement]?.[
                          name as keyof CardElementStyles
                        ] as string
                      )}
                      min={0}
                      max={15}
                      placeholder={placeholder}
                      onChange={(name, value) => {
                        handleStyleChange(name, `${value}px`);
                      }}
                    />
                  ))}
                </InputGroup>
              </div>
            </>
          )}
        </>
      </Modal>

      <Modal
        isOpen={isOpenOptionsModal}
        onClose={() => setIsOpenOptionsModal(false)}
        title={`${localization.change_display_options} ${selectedPostType}`}
        modalActions={[
          {
            text: localization.save,
            type: "button",
            onClickHandler: handleSavePostOptions,
            disabled: !displayOptionsHasChanges,
          },
          {
            text: localization.cancel,
            variant: "secondary",
            type: "button",
            onClickHandler: handleCloseOptionsModal,
          },
        ]}
      >
        <div className="configuration-customizableCard-description-container">
          <p className="configuration-modalDescription">
            {`${localization.display_options_modal} ${selectedPostType}`}
          </p>
          <div className="configuration-customizableCardContainer--displayOptions--preview">
            {settings.results_style == "fancy_card"
              ? generateFancyCard()
              : settings.results_style == "customizable_card"
              ? generateCustomizableCard(false)
              : generateSearchResultsCard()}
          </div>
        </div>
        <Select
          key="category"
          id="category"
          name="category"
          value={displayOptions?.[selectedPostType]?.category || ""}
          label={localization.category}
          onChange={updateTaxonomyConfig}
          placeholder={localization.category_placeholder}
          options={getTaxonomiesOptions(
            topPostsData.dataTypeDisplayOptions,
            selectedPostType
          )}
          onClear={() => onClearTaxonomies(["category"])}
        />
        {settings.results_style !== "fancy_card" && (
          <Select
            key="tag"
            id="tag"
            name="tag"
            value={displayOptions?.[selectedPostType]?.tag || ""}
            label={localization.tag}
            onChange={updateTaxonomyConfig}
            placeholder={localization.tag_placeholder}
            options={getTaxonomiesOptions(
              topPostsData.dataTypeDisplayOptions,
              selectedPostType
            )}
            onClear={() => onClearTaxonomies(["tag"])}
          />
        )}
        <Checkbox
          label={"Show Data Type"}
          onChange={() => {
            setShowDataType(!showDataType);
          }}
          checked={showDataType}
        />
        <div className="configuration-dataType">
          <div className="configuration-dataTypeSelector">
            <Select
              key="data_type"
              id="data_type"
              name="data_type"
              value={displayOptions?.[selectedPostType]?.data_type || ""}
              label={localization.data_type}
              onChange={updateTaxonomyConfig}
              placeholder={localization.type_placeholder}
              options={[
                { text: `${selectedPostType}`, value: selectedPostType },
                ...getTaxonomiesOptions(
                  topPostsData.dataTypeDisplayOptions,
                  selectedPostType
                ),
              ]}
              onClear={() => onClearTaxonomies(["data_type"])}
            />
          </div>

          {displayOptions?.[selectedPostType]?.data_type ==
            selectedPostType && (
            <Button
              text={localization.display_name}
              variant="text"
              onClickHandler={() => setShowPostTypeInput(!showPostTypeInput)}
              size="md"
            />
          )}
        </div>
        {showPostTypeInput &&
          displayOptions?.[selectedPostType]?.data_type ===
            selectedPostType && (
            <div
              className="configuration-displayName-inputField"
              ref={NoDefaultLangPopoverRef}
            >
              {topPostsData.languages.length > 0 ? (
                <InputGroup groupTitle="Post Name">
                  {topPostsData.languages.map((language, index) => (
                    <UpgradePopover
                      open={openPopover == index}
                      content={
                        <div className="configuration-Lang-popoverContent">
                          {popoverContent}
                        </div>
                      }
                    >
                      {" "}
                      <div
                        className="configuration-postName-container"
                        onClick={() =>
                          !isPremium &&
                          language.code !== topPostsData.defaultLanguage &&
                          setOpenPopover(index)
                        }
                      >
                        <InputField
                          key={language.code}
                          type="text"
                          name={"post_name"}
                          placeholder={`${localization.display_name_placeholder} ${language.code}...`}
                          value={postNameObject(language.code) || ""}
                          onChange={(name, value) => {
                            handlePostName(name, value, language.code);
                          }}
                          concatenatedString={language.code}
                          disabled={
                            !isPremium &&
                            language.code !== topPostsData.defaultLanguage
                          }
                        />
                        {!isPremium &&
                          language.code !== topPostsData.defaultLanguage && (
                            <div className="configuration-postName-lockIcon">
                              {LockIcon}
                            </div>
                          )}
                      </div>
                    </UpgradePopover>
                  ))}
                </InputGroup>
              ) : (
                <InputField
                  type="text"
                  name={"post_name"}
                  label={localization.display_name}
                  placeholder={localization.display_name}
                  value={postNameValue}
                  onChange={(name, value) => {
                    handleDefaultPostName(name, value);
                  }}
                />
              )}
            </div>
          )}
      </Modal>
    </div>
  );
};

export default Configuration;
