import {
  ArrowDown,
  CircleIcon,
  MoreHorizIcon,
  OpenNewPage,
  RefreshIcon,
  WarningIcon,
  CopyIcon,
  TrashCanIcon,
  LockIcon,
  SaveAsCopy,
} from "@app/assets/images/icons";
import CardContent from "@app/components/card-content/CardContent";
import CardHeader from "@app/components/card-header/CardHeader";
import Card from "@app/components/card/Card";
import Select from "@app/components/select/Select";
import NoFiltersAnimation from "@app/assets/lotties/No-Filters.json";
import Lottie from "react-lottie";
import * as PopoverPrimitive from "@radix-ui/react-popover";

import {
  ButtonProps,
  CTACardProps,
  CardHeaderProps,
  CustomizableCardProps,
  FieldsOption,
  Filters,
  MenuOption,
  ResultCardProps,
  SelectOption,
} from "@app/models/components";
import {
  Filter,
  Language,
  SingleUrl,
  TopPostsSettings,
} from "@app/models/global";
import React, { useState, useEffect, useMemo, useRef } from "react";
import "./top-posts-manager-styles.scss";
import Skeleton from "@app/components/skeleton/Skeleton";
import { useTopPostsManager } from "@settings/contexts/TopPostsManagerContext";
import {
  DeleteFilterPayload,
  FilterDataPayload,
  UpdateFilterPayload,
  UrlData,
} from "@app/models/api";
import {
  checkUrlDataType,
  deleteFilter,
  getFilter,
  getFilters,
  updateFilter,
  updateTopPostsSettings,
} from "@app/services/api";
import { useSettings } from "@settings/contexts/SettingsContext";
import { useViewMode } from "@settings/contexts/ViewModeContext";
import { Oval } from "react-loader-spinner";
import EmptyState from "@app/components/EmptyState/EmptyState";
import Button from "@app/components/button/Button";
import NumberInput from "@app/components/number-input/NumberInput";
import {
  convertToEasternArabic,
  dateRangeToSeconds,
  ensureDateRangeObject,
  mapTaxonomyToName,
  normalizeRangeForHeaders,
  renderType,
  secondsToDateRange,
} from "@app/services/utilities";

import SelectableChip from "@app/components/selectable-chip/SelectableChip";
import Modal from "@app/components/modal/Modal";
import InputField from "@app/components/input-field/InputField";
import { Controller, useForm } from "react-hook-form";
import Menu from "@app/components/menu/Menu";
import { isEmpty, isEqual, isNumber } from "lodash";

import Tooltip from "@app/components/Tooltip/Tooltip";
import ResultCard from "@app/components/result-card/ResultCard";
import CTACard from "@app/components/CTACard/CTACard";
import DateRangePicker from "@app/components/date-range-picker/DateRangePicker";
import { DateRange } from "react-day-picker";
import CustomizableCard from "@app/components/customizableCard/CustomizableCard";
import { useDateRangePicker } from "@app/components/date-range-picker/DateRangePickerContext";

import UpgradePopover from "@app/components/UpgradePopover/UpgradePopover";
import {
  ActivePopover,
  useUpgradePopover,
} from "@settings/contexts/UpgradePopoverContext";
import InfiniteScroll from "@app/components/InfiniteScroll/InfiniteScroll";
import FilterInfo from "@app/components/filterInfo/FilterInfo";
import SkeletonCard from "@app/components/skeleton-card/SkeletonCard";

const TopPostsManager = () => {
  const { isPremium } = process.env.CONFIG;
  const [posts, setPosts] = useState<Array<UrlData>>([]);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [isFetching, setIsFetching] = useState(false);
  const [isSavingFilteredPosts, setIsSavingFilteredPosts] = useState(false);
  const [isDeletingFilteredPosts, setIsDeletingFilteredPosts] = useState(false);

  const [filteredPosts, setFilteredPosts] = useState<Array<UrlData>>([]);
  const [resetPosts, setResetPosts] = useState<Array<UrlData>>([]);
  const [limit, setLimit] = useState<number>(isPremium ? 500 : 5);
  const [selectedFilter, setSelectedFilter] = useState<number>(-1);
  const [previousSelectedFilter, setPreviousSelectedFilter] =
    useState<number>(-1);
  const [showFilters, setShowFilters] = useState(false);
  const [isOpenDeleteFilterModal, setIsOpenDeleteFilterModal] = useState(false);
  const [isOpenAddFilterModal, setIsOpenAddFilterModal] = useState(false);
  const [isSavingFilterInfo, setIsSavingFilterInfo] = useState(false);
  const [filterDetails, setFilterDetails] = useState({
    filter_name: "",
    description: "",
    slug: "",
  });
  const [currentFilterDetails, setCurrentFilterDetails] = useState({
    filter_name: "",
    description: "",
    slug: "",
  });

  const [isMenuOpen, setIsMenuOpen] = useState(false);
  const [isFilterMenuOpen, setIsFilterMenuOpen] = useState(false);
  const [currentFilterId, setCurrentFilterId] = useState("");

  const [checkUrlDataResponses, setCheckUrlDataResponses] = useState<any>({});

  const { isCustomRange } = useDateRangePicker();

  const {
    initialSettings,
    showNotification,
    setInitialSettings,
    homeURLs,
    dateRangeOptions,
    scopeOptions,
  } = useSettings();
  const { filters, setFilters } = useTopPostsManager();
  const { isRTL } = useViewMode();
  const { control, handleSubmit, reset } = useForm<Filter>({
    mode: "all",
  });
  const [pinnedPosts, setPinnedPosts] = useState<Array<string>>([]);

  const [excludedPosts, setExcludedPosts] = useState<Array<string>>([]);

  const countFilter = (selectedFilter: number) => {
    if (selectedFilter != -1) {
      return `My Filter ${userFilters.length}`;
    } else {
      return `My Filter ${userFilters.length + 1}`;
    }
  };

  const generateFilterSlug = (selectedFilter: number) => {
    if (selectedFilter != -1) {
      return `my-filter-${userFilters.length} `;
    } else {
      return `my-filter-${userFilters.length + 1} `;
    }
  };

  const { microSiteURL } = process.env.CONFIG;
  const localization = topPostsI18n.data;
  const popoverContent = (
    <>
      <p className="manager-popoverContentTitle">
        <b>{localization.top_posts_for_google_analytics}</b>
      </p>
      <Button
        id="manager-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 { activePopover, setActivePopover } = useUpgradePopover();
  const [open, setOpen] = useState("");

  const handleSelectAll = () => {
    handleFilterChange("scope", "post");
  };

  const handleLimitChange = (name: string, value: string | number | null) => {
    const newLimit = Number(value);

    // Open popover if newLimit exceeds 5
    if (!isPremium && newLimit > 5) {
      setActivePopover(ActivePopover.Limit);
      return;
    } else {
      setLimit(newLimit);
      setActivePopover(ActivePopover.None);
    }
  };
  const [showSelectOptions, setShowSelectOptions] = useState(false);

  const scopePopoverRef = useRef<HTMLDivElement>(null);
  const languagePopoverRef = useRef<HTMLDivElement>(null);
  const limitPopoverRef = useRef<HTMLDivElement>(null);
  const datePopoverRef = useRef<HTMLDivElement>(null);
  const addFilterPopoverRef = useRef<HTMLDivElement>(null);
  const saveAsCopyPopoverRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const refs = [
        scopePopoverRef,
        languagePopoverRef,
        limitPopoverRef,
        addFilterPopoverRef,
        datePopoverRef,
        saveAsCopyPopoverRef,
      ];
      const isClickOutside = refs.every(
        (ref) => ref.current && !ref.current.contains(event.target as Node)
      );

      if (isClickOutside) {
        setActivePopover(ActivePopover.None);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [setActivePopover]);

  const toastPosition = isRTL ? "top-left" : "top-right";
  const noFiltersSelected =
    !filters.language && !filters.scope && !filters.date_range;

  const userFilters = useMemo<Filter[]>(() => {
    return initialSettings?.filters
      ? Object.keys(initialSettings.filters).map((key) => ({
          id: key,
          ...(initialSettings?.filters?.[key] as Filter),
        }))
      : [];
  }, [initialSettings?.filters]);

  const transformFiltersObjectToArray = (
    filters: Record<string, Filter>
  ): Filter[] => {
    return Object.keys(filters).map((key) => ({
      id: key,
      ...(filters[key as keyof typeof filters] as Filter),
    }));
  };

  const handleCheckUrlDataType = async (
    urlData: SingleUrl[],
    scope: string | ""
  ) => {
    let remainingURLs: SingleUrl[] = [];
    let checkUrlDataTypeResp: any = [];

    urlData.forEach((ele: SingleUrl) => {
      if (!Object.keys(checkUrlDataResponses).includes(ele.url)) {
        remainingURLs.push(ele);
      } else {
        checkUrlDataTypeResp.push(checkUrlDataResponses[ele.url]);
      }
    });

    const response = await checkUrlDataType(remainingURLs, scope);
    let addCheckUrlDataTypeResponses: any = {};

    response.forEach((item: any) => {
      if (!Object.keys(checkUrlDataResponses).includes(item.original_url)) {
        addCheckUrlDataTypeResponses[item.original_url] = item;
      }
    });

    setCheckUrlDataResponses({
      ...checkUrlDataResponses,
      ...addCheckUrlDataTypeResponses,
    });

    return [...response, ...checkUrlDataTypeResp];
  };

  const handleFilterCall = async (
    selectedFilter: number,
    newSettings = null,
    shouldUpdate = true,
    filterId = "",
    isFilterInfo = false,
    updatedSetting = null,
    updateFilterResp = null,
    updatedFilterDetails: FilterDetails = {}
  ) => {
    setIsOpenAddFilterModal(false);

    let lastModifiedSince = "";
    let response;
    if (
      userFilters?.[selectedFilter]?.filterPosts &&
      Array.isArray(userFilters[selectedFilter].filterPosts) &&
      !!userFilters?.[selectedFilter]?.filterPosts?.length
    ) {
      lastModifiedSince = userFilters?.[selectedFilter]?.lastModified ?? "";
      setPosts(userFilters?.[selectedFilter]?.filterPosts ?? []);
    } else {
      if (isFilterInfo) {
        setIsFetching(false);
      } else {
        setIsFetching(true);
      }
    }

    if (selectedFilter == -1 && !filterId) {
      //-1 but filter_id
      setIsFetching(false);
      return;
    } else if (selectedFilter != -1) {
      filterId = userFilters?.[selectedFilter]?.id ?? "";
    }

    if (!updateFilterResp) {
      response = await getFilter(
        initialSettings.api_key || "",
        filterId,
        lastModifiedSince
      );
      if (response?.error) {
        setIsFetching(false);
        let errorMessage = localization.fetching_filters_error;
        showNotification(
          "error",
          `${errorMessage} (${localization.error} ${response?.status})`,
          toastPosition
        );
        return;
      }

      if (response?.status === 304) {
        setIsFetching(false);
        return;
      }
    } else {
      response = updateFilterResp;
    }

    let lastModified = response.lastModified ?? "";

    let checkUrlDataTypeResp = await handleCheckUrlDataType(
      response.data ?? [],
      ""
    );

    if (lastModified && shouldUpdate) {
      await updateFilterInSettings(
        filterId,
        lastModified,
        newSettings,
        checkUrlDataTypeResp,
        updatedSetting,
        updatedFilterDetails
      );
    }
    if (isFilterInfo) {
      return;
    } else {
      setPosts(checkUrlDataTypeResp);
      setIsFetching(false);
    }
  };

  interface FilterDetails {
    filter_name?: string;
    description?: string;
    slug?: string;
    scope?: string;
    language?: string;
    limit?: number;
    date_range?: DateRange;
  }

  const updateFilterInSettings = async (
    filterId: string,
    lastModified: string,
    newTopPostsSettings: null | TopPostsSettings = null,
    newPosts: any[] = [],
    updatedSettings = null,
    updatedFilterDetails: FilterDetails = {}
  ) => {
    ///// add 1 second to the last modified date   /////
    const lastModifiedDate = new Date(lastModified);
    lastModifiedDate.setSeconds(lastModifiedDate.getSeconds() + 1);
    const updatedLastModified = lastModifiedDate.toUTCString();
    ///// -----  //////

    let localSettings =
      newTopPostsSettings ?? updatedSettings ?? initialSettings;

    if (localSettings.filters && filterId) {
      if (filterId) {
        const existingFilter = localSettings.filters[filterId];

        const updatedFilter: Filter = {
          ...existingFilter,
          display_name:
            updatedFilterDetails?.filter_name &&
            updatedFilterDetails.filter_name !== ""
              ? updatedFilterDetails.filter_name
              : filterDetails.filter_name,

          page: {
            ...existingFilter?.page,
            slug:
              updatedFilterDetails?.slug && updatedFilterDetails.slug !== ""
                ? updatedFilterDetails.slug
                : filterDetails?.slug, // Use fallback to filterDetails if updatedFilterDetails is empty
          },

          description:
            updatedFilterDetails?.description &&
            updatedFilterDetails.description !== ""
              ? updatedFilterDetails.description
              : filterDetails.description,

          date_range: updatedFilterDetails?.date_range
            ? dateRangeToSeconds(updatedFilterDetails?.date_range)
            : dateRangeToSeconds(filters.date_range),
          pinned: pinnedPosts,
          excluded: excludedPosts,
          language:
            updatedFilterDetails?.language ||
            updatedFilterDetails.language == ""
              ? updatedFilterDetails.language
              : filters.language,
          scope:
            updatedFilterDetails?.scope || updatedFilterDetails.scope == ""
              ? updatedFilterDetails.scope.split(",")
              : filters?.scope?.split(","),

          limit: updatedFilterDetails?.limit || limit,
          lastModified: updatedLastModified,
          ...(newPosts.length && {
            filterPosts: applyFilterLogic(
              newPosts,
              updatedFilterDetails?.scope || updatedFilterDetails.scope == ""
                ? updatedFilterDetails.scope
                : filters?.scope || "",
              updatedFilterDetails?.language ||
                updatedFilterDetails.language == ""
                ? updatedFilterDetails.language
                : filters.language,
              limit
            ),
          }),
        };

        const newSettings = {
          ...localSettings,
          filters: {
            ...localSettings.filters,
            [filterId]: updatedFilter,
          },
        };
        const settingsChanged = !isEqual(newSettings, localSettings);
        if (settingsChanged) {
          const updateSettingsResp = await updateTopPostsSettings(newSettings);
          if (updateSettingsResp?.error) {
            setIsSavingFilteredPosts(false);
            setIsOpenAddFilterModal(false);
            return;
          }
          setInitialSettings(updateSettingsResp.updatedSettings);
          //for selecting new filter
          const userFiltersArray = transformFiltersObjectToArray(
            updateSettingsResp.updatedSettings.filters
          );

          const matchingIndex = userFiltersArray.findIndex(
            (filter) => filter?.id === filterId
          );

          if (matchingIndex !== -1) {
            setSelectedFilter(matchingIndex);
          } else {
            setSelectedFilter(0); // Optionally handle case when no match is found
          }
        }
      }
    }
  };

  const fetchData = async (withSync: boolean) => {
    setIsFetching(true);
    if (!initialSettings.site_id) {
      return;
    }
    const existingFilters = await syncFiltersBetweenWPAndCF(withSync);

    if (!isEmpty(existingFilters)) {
      setIsFetching(false);
      return;
    } else {
      setIsFetching(false);
      setShowFilters(false);
      return;
    }
  };

  const [isUpdatingFilter, setIsUpdatingFilter] = useState(false);
  const [isEditing, setIsEditing] = useState(false);

  useEffect(() => {
    if (!isUpdatingFilter && userFilters.length > 0) {
      handleFilterSelect(0, true);
    }
  }, [userFilters, isUpdatingFilter]);

  useEffect(() => {
    fetchData(true);
  }, []);

  const handleDateChange = (range?: DateRange, isCustom?: boolean) => {
    if (!range) {
      return;
    }

    handleFilterChange("date_range", range);
    setPosts([]);
  };

  const handleOpenMenu = (e: any) => {
    e.stopPropagation();
    setIsMenuOpen(!isMenuOpen);
  };

  const handleOpenFilterMenu = (e: any) => {
    setActivePopover(ActivePopover.None);
    e.stopPropagation();
    setIsFilterMenuOpen(!isFilterMenuOpen);
  };

  const closeFilterMenu = () => {
    setIsFilterMenuOpen(false);
  };

  const handleSaveAsCopy = () => {
    if (isPremium) {
      setIsUpdatingFilter(true);
      setIsOpenAddFilterModal(true);
      setFilterDetails({
        filter_name: "",
        description:
          localization.this_is_a_description_of_this_filter_please_edit_me,
        slug: "",
      });
      setPreviousSelectedFilter(selectedFilter);
      setSelectedFilter(-1);
      setCurrentFilterDetails({
        filter_name: "",
        description: "",
        slug: "",
      });
    } else {
      setActivePopover(ActivePopover.SaveAsCopy);
    }
  };
  const [isChanged, setIsChanged] = useState(false);

  useEffect(() => {
    setIsChanged(true);
  }, [selectedFilter]);

  const handleCancelFilterInfo = () => {
    if (selectedFilter != -1) {
      setFilterDetails({
        filter_name: userFilters[selectedFilter].display_name || "",
        description: userFilters[selectedFilter]?.description || "",
        slug: userFilters[selectedFilter]?.page?.slug || "",
      });
    } else {
      setFilterDetails({
        filter_name: countFilter(-1) || "",
        description:
          localization.this_is_a_description_of_this_filter_please_edit_me,
        slug: generateFilterSlug(-1) || "",
      });
    }
  };

  const savedFilterDetails = {
    filter_name: userFilters?.[selectedFilter]?.display_name,
    description: userFilters?.[selectedFilter]?.description,
    slug: userFilters?.[selectedFilter]?.page?.slug,
  };

  const isFilterDetailsChanged = isEqual(filterDetails, savedFilterDetails);

  // Utility function to check if the slug is still in the default format
  const isDefaultSlug = (slug: string): boolean => {
    return /^my-filter-\d+$/.test(slug.trim());
  };
  const isDefaultName = (name: string): boolean => {
    return /^My Filter \d+$/.test(name.trim());
  };

  // Condition to check for placeholder values
  const isFilterChanged =
    isDefaultName(filterDetails.filter_name) &&
    isDefaultSlug(filterDetails.slug) &&
    filterDetails.description ===
      localization.this_is_a_description_of_this_filter_please_edit_me;

  const canSaveFilter =
    selectedFilter == -1 ? !isFilterChanged : !isFilterDetailsChanged;

  const getFilterMenuOptions = (): MenuOption[] => {
    const options: MenuOption[] = [
      {
        icon: CopyIcon,
        label: localization.copy_shortCode,
        onClick: () => {
          copyToClipboard(
            `[top_posts_block filterid='${userFilters?.[selectedFilter]?.id}']`
          );
        },
      },
      {
        label: localization.save_as_copy,
        onClick: handleSaveAsCopy,
        secondIcon: !isPremium ? LockIcon : null,
        icon: SaveAsCopy,
      },
    ];

    {
      isPremium &&
        options.push({
          icon: TrashCanIcon,
          label: localization.delete_filter,
          onClick: () => setIsOpenDeleteFilterModal(true),
          isDestructive: true,
        });
    }

    return options;
  };

  const handleRefreshPosts = async () => {
    setIsRefreshing(true);
    await fetchData(true);
    setIsRefreshing(false);
  };

  const headerProps: CardHeaderProps = {
    title: localization.top_posts_manager,
    subtitle: localization.manage_posts_subtitle,
    actionButtons: [
      {
        text: localization.refresh,
        type: "button",
        icon: RefreshIcon,
        variant: "secondary",
        shape: "rounded",
        onClickHandler: handleRefreshPosts,
        size: "lg",
        disabled: isFetching || isRefreshing || !posts.length,
      },
    ],
  };

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text);

    showNotification(
      "success",
      localization.copied_to_clipboard,
      toastPosition
    );
  };

  const confirmDeleteFilter = () => {
    handleDeleteFilter(selectedFilter);
    onClearFilter(["scope", "language"]);
    setSelectedFilter(-1);
  };

  const skeletonItems = Array.from({ length: 6 }, (_, index) => index + 1);

  const handleFilterChange = <K extends keyof Filters>(
    name: K,
    value: Filters[K]
  ) => {
    setFilters({ ...filters, [name]: value });
  };

  const handleSelectFilterOption = (name: string, value: string) => {
    if (
      name === "language" &&
      !isPremium &&
      value !== topPostsData.defaultLanguage
    ) {
      setActivePopover(ActivePopover.Language);
      return;
    }

    if (name === "scope" && !isPremium && (value === "post" || value === "")) {
      setActivePopover(ActivePopover.None);
      return;
    }

    if (name === "scope" && !isPremium && value !== "post" && value !== "") {
      setActivePopover(ActivePopover.Scope);
      return;
    }

    const notSelectElements = ["date_range"];
    if (name in filters && !notSelectElements.includes(name)) {
      handleFilterChange(name as keyof Filters, value);
    }
  };

  const slugHasChanged = () => {
    const initialSlug = userFilters?.[selectedFilter]?.page?.slug;
    const currentSlug = filterDetails?.slug;
    return initialSlug !== currentSlug;
  };

  const langHasChanged = () => {
    const initialFilterLang = userFilters?.[selectedFilter]?.language ?? "";
    const currentFilterLang = filters?.language;
    return initialFilterLang !== currentFilterLang;
  };

  const handleFilterSelect = (
    filterIndex: number,
    isSelected: boolean,
    shouldUpdate: boolean = true,
    updatedSettings = null,
    isFirstFilter: boolean = false
  ) => {
    setIsUpdatingFilter(true);
    let updatedFilterDetails;
    const isSingleFilter = userFilters.length === 1;
    const shouldSelect = isSingleFilter || isSelected;
    if (isFirstFilter) {
      setSelectedFilter(shouldSelect ? filterIndex - 1 : -1);
    } else {
      setSelectedFilter(shouldSelect ? filterIndex : -1);
    }

    setPinnedPosts(userFilters?.[filterIndex]?.pinned ?? []);
    setExcludedPosts(userFilters?.[filterIndex]?.excluded ?? []);
    setShowFilters(true);

    if (shouldSelect && userFilters.length > 0) {
      const selectedFilterName = userFilters[filterIndex]?.display_name || "";

      const selectedFilterDescription =
        userFilters[filterIndex]?.description || "";
      const selectedFilterSlug = userFilters[filterIndex]?.page?.slug || "";

      setFilterDetails({
        filter_name: selectedFilterName,
        description: selectedFilterDescription,
        slug: selectedFilterSlug || generateSlugFromTitle(selectedFilterName),
      });

      updatedFilterDetails = {
        filter_name: selectedFilterName,
        description: selectedFilterDescription,
        slug: selectedFilterSlug || generateSlugFromTitle(selectedFilterName),
        scope: userFilters[filterIndex]?.scope?.toString(),
        language: userFilters[filterIndex]?.language,
        date_range:
          ensureDateRangeObject(userFilters[filterIndex]?.date_range) ??
          dateRangeOptions[0].range,
        limit: userFilters[filterIndex]?.limit,
      };

      setCurrentFilterDetails({
        filter_name: selectedFilterName,
        description: selectedFilterDescription,
        slug: selectedFilterSlug || generateSlugFromTitle(selectedFilterName),
      });

      setFilters({
        scope: userFilters[filterIndex]?.scope?.toString() || "",
        language: userFilters[filterIndex]?.language || "",
        date_range:
          ensureDateRangeObject(userFilters[filterIndex]?.date_range) ??
          dateRangeOptions[0].range,
      });
      setLimit(userFilters[filterIndex]?.limit || 0);
    }
    !isSelected && !isSingleFilter && onClearFilter(["scope", "language"]);
    handleFilterCall(
      filterIndex,
      null,
      shouldUpdate,
      "",
      false,
      updatedSettings,
      null,
      updatedFilterDetails
    );
  };

  const handleDeleteFilter = async (indexToDelete: number) => {
    if (indexToDelete === -1) {
      return;
    }
    setIsDeletingFilteredPosts(true);

    const payload: DeleteFilterPayload = {
      site_id: topPostsData.site_id || "",
      filter_id: userFilters && userFilters[selectedFilter]?.id,
    };

    // Prepare new settings
    let newFilteredPosts = { ...initialSettings.filters };
    delete newFilteredPosts[payload?.filter_id || ""];

    if (Object.keys(newFilteredPosts).length === 0) {
      newFilteredPosts = {}; // Ensure it's an empty object
    }

    const newSettings = {
      ...initialSettings,
      filters: newFilteredPosts,
    };

    const updateSettingsResp = await updateTopPostsSettings(newSettings);
    if (updateSettingsResp?.error) {
      let errorMessage =
        updateSettingsResp?.status === 400
          ? updateSettingsResp?.message
          : `${localization.deleting_filter_error}(${localization.error} ${updateSettingsResp?.status})`;
      showNotification("error", errorMessage, toastPosition);
      setIsDeletingFilteredPosts(false);
      return;
    }

    const deleteFilterResp = await deleteFilter(
      initialSettings?.api_key ?? "",
      payload
    );

    if (deleteFilterResp?.error) {
      const restoreSettingsResp = await updateTopPostsSettings(initialSettings);
      let errorMessage = localization.deleting_filter_error;
      showNotification(
        "error",
        `${errorMessage} (${localization.error} ${deleteFilterResp?.status})`,
        toastPosition
      );
      setIsOpenDeleteFilterModal(false);
      setIsDeletingFilteredPosts(false);

      return;
    }

    // Everything worked
    setInitialSettings(updateSettingsResp.updatedSettings);
    setIsOpenDeleteFilterModal(false);
    setIsDeletingFilteredPosts(false);
    // fetchData(false);

    if (indexToDelete != 0) {
      handleFilterSelect(0, true, true, updateSettingsResp.updatedSettings);
    } else if (
      indexToDelete === 0 &&
      Object.keys(newSettings.filters || {}).length === 0
    ) {
      fetchData(false);
    } else {
      handleFilterSelect(
        1,
        true,
        false,
        updateSettingsResp.updatedSettings,
        true
      );
    }
  };

  const langSelectOptions: SelectOption[] = topPostsData.languages.map(
    (lang: Language) => ({
      value: lang.code,
      text: lang.native_name,
      icon:
        lang.code !== topPostsData.defaultLanguage && !isPremium
          ? LockIcon
          : null,
    })
  );

  const handleSaveFilterInfo = async () => {
    setIsSavingFilterInfo(true);
    setIsUpdatingFilter(true);
    setCurrentFilterDetails(filterDetails);

    let localFilterId = currentFilterId; // Store the currentFilterId locally
    let updateFilterResp;
    if (initialSettings.filters && selectedFilter !== -1) {
      const filterId = userFilters[selectedFilter]?.id;
      if (filterId) {
        const existingFilter = initialSettings.filters[filterId];

        if (!filterDetails.filter_name) {
          setIsSavingFilterInfo(false);
          setIsUpdatingFilter(false);
          return;
        }

        const updatedFilter: Filter = {
          ...existingFilter,
          display_name: filterDetails.filter_name,
          page: {
            ...existingFilter?.page,
            slug: filterDetails?.slug
              ? filterDetails?.slug
              : generateSlugFromTitle(filterDetails.filter_name),
          },
          description: filterDetails.description,
        };

        const newSettings = {
          ...initialSettings,
          filters: {
            ...initialSettings.filters,
            [filterId]: updatedFilter,
          },
        };

        const hasChanged = isEqual(
          newSettings.filters,
          initialSettings.filters
        );

        if (hasChanged) {
          showNotification(
            "success",
            localization.filter_is_already_saved,
            toastPosition
          );
          setIsSavingFilterInfo(false);
          return;
        }

        if (!filterDetails.slug) {
          setFilterDetails({
            ...filterDetails,
            slug: generateSlugFromTitle(filterDetails.filter_name),
          });
        }

        const { filterPosts, lastModified, ...rest } = updatedFilter || {};

        const payload: UpdateFilterPayload = {
          site_id: topPostsData.site_id || "",
          filter_data: rest,
          filter_id: filterId, // Use the local filterId here
        };

        if (selectedFilter !== -1) {
          updateFilterResp = await updateFilter(
            initialSettings?.api_key ?? "",
            payload
          );
          if (updateFilterResp?.filter_id) {
            localFilterId = updateFilterResp.filter_id; // Update the local filterId
          }
        }
      }
      await handleFilterCall(
        selectedFilter,
        null,
        true,
        localFilterId,
        true,
        null,
        updateFilterResp
      );
    } else {
      await handleSaveNewFilter(true);
    }

    setIsSavingFilterInfo(false);
    setIsSavingFilteredPosts(false);
    setCurrentFilterId("");
  };

  const handleSaveNewFilter = async (isFilterInfo = false) => {
    if (!isFilterInfo) {
      setIsSavingFilteredPosts(true);
    }

    setIsUpdatingFilter(true);

    let dateRange: number | DateRange = dateRangeToSeconds(
      dateRangeOptions[0].range
    );

    if (filters.date_range && !isCustomRange) {
      dateRange = dateRangeToSeconds(filters.date_range);
    } else if (filters.date_range) {
      dateRange = filters.date_range;
    }

    // Variable to hold the updated filter data
    let updatedFilter: Filter;

    if (!isFilterInfo) {
      updatedFilter = {
        display_name: filterDetails.filter_name,
        page: {
          slug: filterDetails.slug,
        },
        description: filterDetails.description,
        pinned: pinnedPosts,
        excluded: excludedPosts,
        limit: limit,
        scheduled_trigger: initialSettings?.scheduled_trigger,
      };

      if (isNumber(dateRange)) {
        updatedFilter.date_range = dateRange;
      } else {
        updatedFilter.custom_date_range = dateRange;
      }

      if (filters?.language?.trim()) {
        updatedFilter.language = filters.language;
      }

      if (filters?.scope?.trim()) {
        updatedFilter.scope = filters.scope.split(",");
      }
    } else {
      updatedFilter = {
        display_name: filterDetails.filter_name,
        page: {
          slug: filterDetails.slug,
        },
        description: filterDetails.description,
        limit: 500,
        date_range: dateRangeToSeconds(filters.date_range),
      };
    }

    // Construct the payload based on updatedFilter
    const payload: UpdateFilterPayload = {
      site_id: topPostsData.site_id || "",
      filter_data: updatedFilter,
    };

    if (currentFilterId?.trim()) {
      payload.filter_id = currentFilterId;
    }

    // Send the request to create the filter
    const updateFilterResp = await updateFilter(
      initialSettings.api_key || "",
      payload
    );

    if (updateFilterResp?.error) {
      setIsFetching(false);
      let errorMessage = localization.fetching_filters_error;
      showNotification(
        "error",
        `${errorMessage} (${localization.error} ${updateFilterResp?.status})`,
        toastPosition
      );
      return;
    }

    let lastModified = updateFilterResp.lastModified ?? "";
    let checkUrlDataTypeResp = await handleCheckUrlDataType(
      updateFilterResp.data ?? [],
      ""
    );

    const newSettings: TopPostsSettings = {
      ...initialSettings,
      filters: {
        ...initialSettings.filters,
        [updateFilterResp.filter_id]: updatedFilter,
      },
    };

    if (lastModified) {
      await updateFilterInSettings(
        updateFilterResp.filter_id,
        lastModified,
        newSettings,
        checkUrlDataTypeResp
      );
    }
    if (!isFilterInfo) {
      setPosts(checkUrlDataTypeResp);
    }

    setIsFetching(false);
  };

  const handleSaveFilteredPosts = async () => {
    setIsSavingFilteredPosts(true);
    setIsUpdatingFilter(true);

    let dateRange: number | DateRange = dateRangeToSeconds(
      dateRangeOptions[0].range
    );

    if (filters.date_range && !isCustomRange) {
      dateRange = dateRangeToSeconds(filters.date_range);
    } else if (filters.date_range) {
      dateRange = filters.date_range;
    }

    let localFilterId = currentFilterId; // Store the currentFilterId locally
    let updateFilterResp;
    if (initialSettings.filters && selectedFilter !== -1) {
      const filterId = userFilters[selectedFilter]?.id;
      if (filterId) {
        const existingFilter = initialSettings.filters[filterId];

        const updatedFilter: Filter = {
          ...existingFilter,
          display_name: filterDetails.filter_name,
          page: {
            ...existingFilter?.page,
            slug: filterDetails?.slug,
          },
          description: filterDetails.description,
          pinned: pinnedPosts,
          excluded: excludedPosts,
          language: filters.language,
          scope: filters?.scope?.split(","),
          limit: limit,
          filterPosts: applyFilterLogic(
            posts,
            filters?.scope || "",
            filters.language || "",
            limit
          ),
        };
        if (isNumber(dateRange)) {
          updatedFilter.date_range = dateRange;
        } else {
          updatedFilter.custom_date_range = dateRange;
        }

        const newSettings = {
          ...initialSettings,
          filters: {
            ...initialSettings.filters,
            [filterId]: updatedFilter,
          },
        };

        const hasChanged = isEqual(
          newSettings.filters,
          initialSettings.filters
        );

        if (hasChanged) {
          showNotification(
            "success",
            localization.filter_is_already_saved,
            toastPosition
          );
          setIsSavingFilteredPosts(false);
          setIsOpenAddFilterModal(false);
          return;
        }

        const { filterPosts, lastModified, ...rest } = updatedFilter || {};

        const payload: UpdateFilterPayload = {
          site_id: topPostsData.site_id || "",
          filter_data: rest,
          filter_id: filterId, // Use the local filterId here
        };

        if (selectedFilter !== -1) {
          updateFilterResp = await updateFilter(
            initialSettings?.api_key ?? "",
            payload
          );
          if (updateFilterResp?.filter_id) {
            localFilterId = updateFilterResp.filter_id; // Update the local filterId
          }
        }
      }

      await handleFilterCall(
        selectedFilter,
        null,
        true,
        filterId,
        false,
        null,
        updateFilterResp
      );
    } else {
      await handleSaveNewFilter();
    }

    setIsOpenAddFilterModal(false);
    setIsSavingFilteredPosts(false);
    setCurrentFilterId("");
  };

  const handleInputChange = (name: string, value: string) => {
    setFilterDetails((prevDetails) => {
      let defaultValue = value;

      const updatedDetails = { ...prevDetails, [name]: defaultValue };

      if (
        name === "filter_name" &&
        (isDefaultSlug(currentFilterDetails.slug) ||
          currentFilterDetails.slug === "")
      ) {
        const newSlug = generateSlugFromTitle(value);
        return {
          ...prevDetails,
          filter_name: defaultValue,
          slug: newSlug,
        };
      }

      return updatedDetails;
    });
  };

  const handleFieldChange = (value: string, field: any) => {
    field.onChange(value);

    handleInputChange(field.name, value);
  };

  const generateSlugFromTitle = (title: string) => {
    return title.trim().replace(/\s+/g, "-").toLowerCase();
  };

  const filterFields = [
    {
      name: "slug",
      value: filterDetails.slug,
      type: "text",
      variant: "secondary",
      concatenatedValue:
        homeURLs?.[filters.language || "default"] ?? topPostsData.homeURL,
      slugHasChanged: slugHasChanged(),
      langHasChanged: langHasChanged(),
      link: userFilters[selectedFilter]?.page?.url,
      icon: OpenNewPage,
    },
    {
      name: "filter_name",
      value: filterDetails.filter_name,

      type: "text",
      variant: "primary",
    },

    {
      name: "description",
      value: filterDetails.description,

      type: "paragraph",
    },
  ];

  const isDefaultDescription = () => {
    return (
      filterDetails.description ===
      "This is a description of this filter. Please edit me."
    );
  };

  const onClearFilter = (filtersToClear: ("scope" | "language")[]) => {
    const updatedFilters = { ...filters };
    filtersToClear.forEach((filter) => {
      updatedFilters[filter] = "";
    });
    setFilters(updatedFilters);
  };

  const syncFiltersBetweenWPAndCF = async (withSync: boolean) => {
    const getFiltersResponse = await getFilters(
      initialSettings?.api_key ?? "",
      topPostsData.site_id ?? ""
    );
    if (getFiltersResponse?.error) {
      let errorMessage = localization.saving_settings_error;
      showNotification(
        "error",
        `${errorMessage} (${localization.error} ${getFiltersResponse?.status})`,
        toastPosition
      );
      return null;
    }

    const { filters } = getFiltersResponse;
    let filtersToUpdate = { ...filters };

    if (!withSync) {
      return filtersToUpdate;
    }

    let filtersInWp = Object.keys(initialSettings?.filters || {}).map(
      (key: string, item: any) => key
    );
    let filtersInCF = Object.keys(filtersToUpdate || {}).map(
      (key: string, item: any) => key
    );

    // Items in filtersInWp but not in filtersInCF
    const uniqueToWp = filtersInWp.filter((key) => !filtersInCF.includes(key));

    // Items in filtersInCF but not in filtersInWp
    const uniqueToCF = filtersInCF.filter((key) => !filtersInWp.includes(key));

    // Combine results to get non common filters
    const nonCommonItems = [...uniqueToWp, ...uniqueToCF];

    if (!nonCommonItems.length) {
      return filtersToUpdate;
    }
    nonCommonItems.forEach(async (filterId) => {
      if (uniqueToCF.includes(filterId)) {
        const payload: DeleteFilterPayload = {
          site_id: topPostsData.site_id || "",
          filter_id: filterId,
        };
        const deleteFilterResp = await deleteFilter(
          initialSettings?.api_key ?? "",
          payload
        );

        if (deleteFilterResp?.error) {
          let errorMessage = localization.failed_delete_configuration_error;
          showNotification(
            "error",
            `${errorMessage} (${localization.error} ${deleteFilterResp?.status})`,
            toastPosition
          );
          return null;
        }
        delete filtersToUpdate[filterId];
      } else if (uniqueToWp.includes(filterId)) {
        let newFilters = { ...initialSettings.filters };
        delete newFilters[filterId || ""];

        if (Object.keys(newFilters).length === 0) {
          newFilters = {}; // Ensure it's an empty object
        }

        const newSettings = {
          ...initialSettings,
          filters: newFilters,
        };

        const updateSettingsResp = await updateTopPostsSettings(newSettings);
        if (updateSettingsResp?.error) {
          let errorMessage =
            updateSettingsResp?.status === 400
              ? updateSettingsResp?.message
              : `${localization.deleting_filter_error}(${localization.error} ${updateSettingsResp?.status})`;
          showNotification("error", errorMessage, toastPosition);
          return null;
        }
        delete filtersToUpdate[filterId];
        setInitialSettings(updateSettingsResp.updatedSettings);
      }
    });

    return filtersToUpdate;
  };

  const getDateRange = (
    dateRange: string | number | DateRange | undefined
  ): DateRange | undefined => {
    if (typeof dateRange === "number" || typeof dateRange === "string") {
      return secondsToDateRange(dateRange);
    }
    return undefined;
  };

  const filterOptions = {
    ...filters,
    limit,
    date_range: getDateRange(dateRangeToSeconds(filters.date_range)),
  };

  const savedFilterOptions = {
    scope: userFilters[selectedFilter]?.scope?.join(",") || "",
    language: userFilters[selectedFilter]?.language || "",
    date_range: getDateRange(userFilters[selectedFilter]?.date_range),
    limit: userFilters[selectedFilter]?.limit,
  };

  const isResetFilterActive = isEqual(filterOptions, savedFilterOptions);

  useEffect(() => {
    if (!isResetFilterActive) {
      setFilteredPosts([]);
    }
  }, [filters, limit]);

  const applyFilterLogic = (
    posts: UrlData[],
    scope: string,
    language: string,
    limit: number = 0
  ): UrlData[] => {
    if (isPremium) {
      if (scope.trim()) {
        posts = posts.filter((post) => scope.split(",").includes(post.type));
      }

      if (language.trim()) {
        posts = posts.filter((post) => post.language === language);
      }
    }

    posts = posts.map((post) => ({
      ...post,
      excluded:
        userFilters?.[selectedFilter]?.excluded?.includes(post?.id) ?? false,
      pinned: userFilters?.[selectedFilter]?.pinned?.includes(post.id) ?? false,
    }));

    const returnedPosts = posts.map((post) => {
      if (isPremium) {
        return post; // If premium, return the post as is
      }

      if (
        (topPostsData.languages.length > 0 &&
          language.trim() &&
          post.language !== filters.language) ||
        post.type !== "post"
      ) {
        return { ...post, excluded: true };
      }

      return post;
    });

    // Sorting: pinned posts at the top, excluded posts at the bottom
    returnedPosts.sort((a, b) => {
      if (a.pinned && !b.pinned) return -1;
      if (!a.pinned && b.pinned) return 1;
      if (a.excluded && !b.excluded) return 1;
      if (!a.excluded && b.excluded) return -1;
      return 0;
    });

    const seenIds = new Set();
    const uniqueResults = returnedPosts.filter((item) => {
      const isDuplicate = seenIds.has(item.id);
      seenIds.add(item.id);
      return !isDuplicate;
    });

    if (limit === 0) {
      return uniqueResults;
    }
    return uniqueResults.slice(0, limit);
  };

  useEffect(() => {
    if (!posts.length) {
      setFilteredPosts([]);
      return;
    }
    if (selectedFilter == -1) {
      return;
    }

    let updatedPosts = [...posts];

    let uniqueResults = applyFilterLogic(
      updatedPosts,
      filters?.scope || "",
      filters?.language || "",
      limit
    );

    setFilteredPosts(uniqueResults);
    setResetPosts(uniqueResults);
  }, [posts, selectedFilter]);

  const isSaveFilterBtnDisabled =
    isSavingFilteredPosts || noFiltersSelected || isSavingFilterInfo;

  const handlePin = (itemId: string | number) => {
    setFilteredPosts((items: any[]) => {
      const updatedPosts = items.map((item) =>
        item.id === itemId
          ? item.excluded
            ? { ...item, excluded: false, pinned: true }
            : { ...item, pinned: !item.pinned }
          : item
      );
      updatedPosts.sort((a, b) =>
        a.pinned === b.pinned ? 0 : a.pinned ? -1 : 1
      );

      const updatedItem = updatedPosts.find((item: any) => item.id === itemId);

      if (updatedItem) {
        if (updatedItem.pinned) {
          setPinnedPosts((prevPinnedPosts) => [
            ...prevPinnedPosts,
            updatedItem.id,
          ]);
          setExcludedPosts((prevExcludedPosts) =>
            prevExcludedPosts.filter((id) => id !== updatedItem.id)
          );
        } else {
          setPinnedPosts((prevPinnedPosts) =>
            prevPinnedPosts.filter((id) => id !== updatedItem.id)
          );
        }
      }

      return updatedPosts;
    });
  };

  const handleExclude = (itemId: string | number) => {
    setFilteredPosts((items: any[]) => {
      const updatedPosts = items.map((item: any) =>
        item.id === itemId
          ? { ...item, excluded: !item.excluded, pinned: false }
          : item
      );

      // Find the updated item
      const updatedItem = updatedPosts.find((item: any) => item.id === itemId);

      if (updatedItem) {
        if (updatedItem.excluded) {
          // Add to excludedPosts if excluded
          setExcludedPosts((prevExcludedPosts) => [
            ...prevExcludedPosts,
            updatedItem.id,
          ]);
          // Remove from pinnedPosts if pinned
          setPinnedPosts((prevPinnedPosts) =>
            prevPinnedPosts.filter((id) => id !== updatedItem.id)
          );
        } else {
          // Remove from excludedPosts if not excluded
          setExcludedPosts((prevExcludedPosts) =>
            prevExcludedPosts.filter((id) => id !== updatedItem.id)
          );
        }
      }

      return updatedPosts;
    });
  };

  const handleCloseFilterModal = () => {
    setSelectedFilter(previousSelectedFilter);
    handleFilterSelect(previousSelectedFilter, true);
    setIsOpenAddFilterModal(false);
    reset();
  };

  const handleResetFilterOptions = () => {
    setFilteredPosts(resetPosts);
    setFilters({
      scope: userFilters[selectedFilter]?.scope?.toString() || "",
      language: userFilters[selectedFilter]?.language || "",
      date_range:
        ensureDateRangeObject(userFilters[selectedFilter]?.date_range) ??
        dateRangeOptions[0].range,
    });
    setLimit(userFilters[selectedFilter]?.limit || 0);
  };

  const handleAddFilterClick = async () => {
    setPosts([]);
    setLimit(500);

    setSelectedFilter(-1);
    setFilterDetails({
      filter_name: countFilter(-1) || "",
      description:
        localization.this_is_a_description_of_this_filter_please_edit_me,
      slug: generateFilterSlug(-1) || "",
    });
    setCurrentFilterDetails({
      filter_name: countFilter(-1) || "",
      description:
        localization.this_is_a_description_of_this_filter_please_edit_me,
      slug: generateFilterSlug(-1) || "",
    });
    setIsUpdatingFilter(true);

    if (selectedFilter === -1 && showFilters) {
      return;
    }

    setFilters({
      scope: "",
      language: "",
      date_range:
        ensureDateRangeObject(initialSettings.date_range) ??
        dateRangeOptions[0].range,
    });
    setShowFilters(true);
  };

  const renderCard = (post: UrlData, index: number) => {
    const pinButton: ButtonProps = {
      text: localization.pin,
      type: "submit",
      onClickHandler: () => handlePin(post.id),
    };

    const unpinButton: ButtonProps = {
      text: localization.unpin,
      type: "submit",
      variant: "secondary",
      onClickHandler: () => handlePin(post.id),
      style: { backgroundColor: "white" },
    };

    const includeButton: ButtonProps = {
      text: localization.include,
      type: "submit",
      onClickHandler: () => handleExclude(post.id),
    };

    const excludeButton: ButtonProps = {
      text: localization.exclude_post,
      type: "submit",
      variant: "secondary",
      onClickHandler: () => handleExclude(post.id),
      style: { backgroundColor: "white" },
    };

    const pinned = post?.pinned || false;
    const excluded = post?.excluded || false;

    const isPostOrCPT =
      post?.type !== "category" &&
      post?.type !== "post_tag" &&
      post?.type !== "page";

    const isPostOrPage = isPostOrCPT || post?.type === "page";

    const actionButtons =
      !isPremium &&
      excluded &&
      (post.language !== topPostsData.defaultLanguage || post.type !== "post")
        ? []
        : selectedFilter !== -1
        ? [
            pinned ? unpinButton : pinButton,
            excluded ? includeButton : excludeButton,
          ]
        : [];

    const hasDate = isPostOrPage && post?.date;
    const date =
      hasDate && post?.language === "ar"
        ? convertToEasternArabic(
            new Date(post.date).toLocaleDateString("ar", {
              day: "2-digit",
              month: "short",
              year: "numeric",
            })
          )
        : hasDate
        ? new Date(post.date).toLocaleDateString("en-GB", {
            day: "2-digit",
            month: "short",
            year: "numeric",
          })
        : "";

    const tags =
      isPostOrCPT && post?.tags
        ? post?.tags.map((tag) => ({
            label: tag.name,
            href: tag.link,
          })) ?? []
        : [];

    const title = (isPostOrCPT ? post?.title : post?.name) ?? "";

    const body = (isPostOrCPT ? post?.excerpt : post?.description) ?? "";

    const category = isPostOrCPT
      ? post?.category[0]
      : mapTaxonomyToName(post?.type);

    let props: CTACardProps | ResultCardProps | null = null;
    const style = initialSettings?.results_style || "search_results_card";

    const getVariant = () => {
      if (isPostOrPage && !pinned) {
        return "PRIMARY";
      } else if (isPostOrPage && pinned) {
        return "PRIMARY_VERTICAL";
      } else if (!isPostOrPage && !pinned) {
        return "SECONDARY";
      } else if (!isPostOrPage && pinned) {
        return "TERTIARY";
      }
    };

    if (style === "fancy_card") {
      props = {
        variant: getVariant(),
        imageSrc: post?.image,
        title,
        tag: category,
        meta: date,
        description: body,
        actionButtons,
        dimmed: excluded,
        onClick: () => post?.url && window.open(post?.url, "_blank"),
        score: post?.score ?? "",
        showActionButtons: true,
        rtl: post?.language == "ar",
        type: initialSettings.show_data_type ? renderType(post) : "",
        lazyLoad: index > 2,
      } satisfies CTACardProps;
    } else if (style === "search_results_card") {
      props = {
        image: post?.image,
        dimmed: excluded,
        href: post?.url,
        actionButtons,
        tags,
        body,
        title,
        category,
        date,
        score: post?.score ? `${localization.page_views} ${post.score}` : "",
        rtl: post?.language == "ar",
        type:
          post?.type == "post" && initialSettings.show_data_type
            ? renderType(post)
            : "",
        lazyLoad: index > 2,
      } satisfies ResultCardProps;
    } else if (style === "customizable_card") {
      props = {
        image: post?.image,
        dimmed: excluded,
        href: post?.url,
        actionButtons,
        tags,
        body,
        title,
        category,
        date,
        score: post?.score ? `${localization.page_views} ${post.score}` : "",
        rtl: post?.language == "ar",
        type:
          post?.type == "post" && initialSettings.show_data_type
            ? renderType(post)
            : "",
        lazyLoad: index > 2,
      } satisfies CustomizableCardProps;
    }
    const popoverKey = `${post.id}-${index}`;

    return (
      <div key={popoverKey} className="manager-gridItem">
        {style === "fancy_card" ? (
          <CTACard {...(props as CTACardProps)} />
        ) : style === "search_results_card" ? (
          !isPremium ? (
            <UpgradePopover
              open={open == popoverKey && actionButtons.length == 0}
              content={
                <div className="manager-addFilter-popoverContent">
                  {popoverContent}
                </div>
              }
            >
              <div
                onMouseOver={() => {
                  setOpen(popoverKey);
                }}
              >
                <ResultCard {...(props as ResultCardProps)} />
              </div>
            </UpgradePopover>
          ) : (
            <ResultCard {...(props as ResultCardProps)} />
          )
        ) : style === "customizable_card" ? (
          <CustomizableCard
            {...(props as CustomizableCardProps)}
            styling={initialSettings.custom_styles}
          />
        ) : null}
      </div>
    );
  };

  const getFlagImg = (filter: Filter) => {
    const hasFlag = filter?.hasOwnProperty("page_id") && filter.language !== "";
    let alt = "";
    if (hasFlag && topPostsData.languages.length > 0) {
      const flagName =
        topPostsData.languages.find(
          (lang: Language) => lang.code === filter.language
        )?.translated_name || "";

      alt = `${flagName} ${localization.flag}`;
    }

    return hasFlag ? (
      <img
        className="manager-flagImage"
        src={`${topPostsData.flagsDirectory}${filter.language}.png`}
        alt={alt}
      />
    ) : undefined;
  };

  const filteredPostsResultCards = useMemo(() => {
    if (!filteredPosts) return null;

    return (
      <InfiniteScroll
        items={filteredPosts.slice(0, limit)}
        itemsToShow={20}
        renderItem={renderCard}
      />
    );
  }, [filteredPosts, open]);

  const renderSkeletonItems = () =>
    skeletonItems?.map((item) => (
      <div key={item} className="manager-gridItem">
        <SkeletonCard variant={initialSettings?.results_style} />
      </div>
    ));

  const getColumnLayoutClass = () => {
    if (
      !initialSettings?.columns_number ||
      initialSettings?.columns_number === 1
    ) {
      return "manager-postsGrid--singleColumn";
    }

    return "manager-postsGrid--twoColumn";
  };

  return (
    <div className="settings-wrapper">
      <Card>
        <CardHeader {...headerProps} id="manager-cardHeader" />
        <div className="manager-savedFilters-section">
          <div className="manager-addFilter-wrapper">
            <h3>{localization.saved_filters}</h3>

            {!isPremium ? (
              <div ref={addFilterPopoverRef}>
                <UpgradePopover
                  open={activePopover === ActivePopover.AddFilter}
                  onOpenChange={() => setActivePopover(ActivePopover.AddFilter)}
                  content={
                    <div className="manager-popoverContent">
                      {popoverContent}
                    </div>
                  }
                >
                  <Button
                    text={localization.add_filter}
                    icon={CircleIcon}
                    onClickHandler={() => {}}
                    variant="tertiary"
                    flagIcon={!isPremium ? LockIcon : null}
                  />
                </UpgradePopover>
              </div>
            ) : (
              <Button
                text={localization.add_filter}
                icon={CircleIcon}
                onClickHandler={handleAddFilterClick}
                variant="tertiary"
                flagIcon={!isPremium ? LockIcon : null}
              />
            )}
          </div>

          {!isEmpty(initialSettings?.filters) ? (
            <div className="manager-selectableChip-wrapper">
              {Object.entries(initialSettings?.filters).map(
                ([key, filter], index) => {
                  if (filter && Object.keys(filter).length > 0) {
                    return (
                      <SelectableChip
                        key={`${key}-${index}`}
                        id={`manager-defaultFilter-${key}`}
                        label={(filter as any).display_name || ""}
                        selected={index === selectedFilter}
                        onSelect={(isSelected) => {
                          handleFilterSelect(index, isSelected);
                          setIsEditing(false);
                        }}
                        disabled={isFetching || isRefreshing}
                        icon={getFlagImg(filter)}
                      />
                    );
                  }
                  return null;
                }
              )}
            </div>
          ) : (
            <p>{localization.empty_filters_subtitle}</p>
          )}
        </div>
        <CardContent id="manager-cardContent">
          {showFilters && (
            <>
              {" "}
              <FilterInfo
                fields={filterFields}
                onChange={handleInputChange}
                onSave={canSaveFilter ? handleSaveFilterInfo : () => {}}
                isLoading={isSavingFilterInfo}
                onCancel={handleCancelFilterInfo}
                isDefaultDescription={isDefaultDescription()}
                isEditing={isEditing}
                setIsEditing={setIsEditing}
              />
              <div className="manager-filtersWrapper" ref={datePopoverRef}>
                {!isPremium ? (
                  <UpgradePopover
                    open={activePopover === ActivePopover.DateRange}
                    onOpenChange={() =>
                      setActivePopover(ActivePopover.DateRange)
                    }
                    content={
                      <div className="manager-popoverContent">
                        {popoverContent}
                      </div>
                    }
                  >
                    <div className="manager-popoverRoot">
                      {" "}
                      <DateRangePicker
                        key="date_range"
                        range={
                          ensureDateRangeObject(filters.date_range) ??
                          dateRangeOptions[0].range
                        }
                        onChange={() => {}}
                        label={localization.date_range}
                        defaultOptions={dateRangeOptions}
                        disabled={isFetching || isRefreshing || !posts.length}
                        showTitle
                        icon={!isPremium ? LockIcon : null}
                      />
                    </div>
                  </UpgradePopover>
                ) : (
                  <DateRangePicker
                    key="date_range"
                    range={
                      ensureDateRangeObject(filters.date_range) ??
                      dateRangeOptions[0].range
                    }
                    onChange={handleDateChange}
                    label={localization.date_range}
                    defaultOptions={dateRangeOptions}
                    disabled={isFetching || isRefreshing}
                    showTitle
                    icon={!isPremium ? LockIcon : null}
                  />
                )}
                {!isPremium ? (
                  <div className="manager-filter" ref={scopePopoverRef}>
                    <UpgradePopover
                      open={activePopover === ActivePopover.Scope}
                      onOpenChange={() => setActivePopover(ActivePopover.None)}
                      content={
                        <div className="manager-scope-popoverContent">
                          {popoverContent}
                        </div>
                      }
                    >
                      <Select
                        id="scope"
                        name="scope"
                        label={localization.scope}
                        value={filters.scope}
                        externalShowOptions={showSelectOptions}
                        onChange={(name, value) => {
                          setShowSelectOptions(false);
                          handleSelectFilterOption(name, value);
                        }}
                        placeholder={localization.scope_placeholder}
                        options={scopeOptions}
                        multiple
                        disabled={isFetching || isRefreshing}
                        handleSelectAll={handleSelectAll}
                      />
                    </UpgradePopover>
                  </div>
                ) : (
                  <div className="manager-filter">
                    <Select
                      id="scope"
                      name="scope"
                      label={localization.scope}
                      value={filters.scope}
                      onChange={handleSelectFilterOption}
                      placeholder={localization.scope_placeholder}
                      options={scopeOptions}
                      multiple
                      onClear={() => onClearFilter(["scope"])}
                      disabled={isFetching || isRefreshing}
                    />
                  </div>
                )}
                {topPostsData?.languages?.length > 0 && (
                  <div className="manager-filter" ref={languagePopoverRef}>
                    {!isPremium ? (
                      <UpgradePopover
                        open={activePopover === ActivePopover.Language}
                        onOpenChange={() =>
                          setActivePopover(ActivePopover.None)
                        }
                        content={
                          <div className="manager-scope-popoverContent">
                            {popoverContent}
                          </div>
                        }
                      >
                        <Select
                          id="language"
                          name="language"
                          label={localization.language}
                          value={filters.language}
                          onChange={handleSelectFilterOption}
                          placeholder={localization.language_placeholder}
                          options={langSelectOptions}
                          disabled={isFetching || isRefreshing}
                        />
                      </UpgradePopover>
                    ) : (
                      <Select
                        id="language"
                        name="language"
                        label={localization.language}
                        value={filters.language}
                        onChange={handleSelectFilterOption}
                        placeholder={localization.language_placeholder}
                        options={langSelectOptions}
                        onClear={() => onClearFilter(["language"])}
                        disabled={isFetching || isRefreshing}
                      />
                    )}
                  </div>
                )}
                <div className="manager-limitFilter manager-filter">
                  {!isPremium ? (
                    <div
                      className="manager-addFilter-popoverRoot"
                      ref={limitPopoverRef}
                    >
                      <UpgradePopover
                        open={activePopover === ActivePopover.Limit}
                        content={
                          <div className="manager-scope-popoverContent">
                            {popoverContent}
                          </div>
                        }
                      >
                        <NumberInput
                          id="limit"
                          name="limit"
                          label={localization.limit}
                          value={limit.toString()}
                          min={1}
                          max={500}
                          placeholder={localization.limit_placeholder}
                          onChange={(name, value) => {
                            handleLimitChange(name, value);
                          }}
                          disabled={isFetching || isRefreshing}
                        />
                      </UpgradePopover>
                    </div>
                  ) : (
                    <NumberInput
                      id="limit"
                      name="limit"
                      label={localization.limit}
                      value={limit.toString()}
                      min={1}
                      max={500}
                      placeholder={localization.limit_placeholder}
                      onChange={(name, value) => {
                        setLimit(Number(value));
                      }}
                      disabled={isFetching || isRefreshing}
                    />
                  )}
                </div>

                <Button
                  id="manager-saveFilterButton"
                  text={localization.save}
                  onClickHandler={handleSaveFilteredPosts}
                  shape="boxy"
                  variant="ghost"
                  size="lg"
                  disabled={isSaveFilterBtnDisabled}
                  isLoading={isSavingFilteredPosts}
                />

                {selectedFilter !== -1 &&
                  (!isPremium ? (
                    <div ref={saveAsCopyPopoverRef}>
                      <UpgradePopover
                        open={activePopover === ActivePopover.SaveAsCopy}
                        onOpenChange={() =>
                          setActivePopover(ActivePopover.SaveAsCopy)
                        }
                        content={
                          <div className="manager-popoverContent-saveAsCopy">
                            {popoverContent}
                          </div>
                        }
                      >
                        <Menu
                          open={isFilterMenuOpen}
                          options={getFilterMenuOptions()}
                          onClose={closeFilterMenu}
                        >
                          <Button
                            id="manager-filterOptionsButton"
                            onClickHandler={handleOpenFilterMenu}
                            icon={MoreHorizIcon}
                            iconPosition="end"
                            shape="boxy"
                            variant="ghost"
                          />
                        </Menu>
                      </UpgradePopover>
                    </div>
                  ) : (
                    <Menu
                      open={isFilterMenuOpen}
                      options={getFilterMenuOptions()}
                      onClose={closeFilterMenu}
                    >
                      <Button
                        id="manager-filterOptionsButton"
                        onClickHandler={handleOpenFilterMenu}
                        icon={MoreHorizIcon}
                        iconPosition="end"
                        shape="boxy"
                        variant="ghost"
                      />
                    </Menu>
                  ))}

                {selectedFilter != -1 && !isResetFilterActive && (
                  <Button
                    text={localization.reset}
                    onClickHandler={handleResetFilterOptions}
                    variant="ghost"
                    size="lg"
                  />
                )}
              </div>
            </>
          )}

          <div className={`manager-postsGrid--outer ${getColumnLayoutClass()}`}>
            {isRefreshing && (
              <div className="manager-postsGrid--overlay">
                <div className="manager-postsGrid--loader">
                  <Oval
                    height={26}
                    width={26}
                    color="#8134af"
                    wrapperStyle={{}}
                    wrapperClass=""
                    visible={true}
                    ariaLabel="oval-loading"
                    secondaryColor="#8134af"
                    strokeWidth={6}
                    strokeWidthSecondary={6}
                  />
                </div>
              </div>
            )}
            {showFilters ? (
              <div className="manager-postsGrid--inner">
                {filteredPosts?.length > 0 && !isFetching
                  ? filteredPostsResultCards
                  : isFetching && !isRefreshing && renderSkeletonItems()}
              </div>
            ) : (
              <div className="manager-emptySpace">
                <EmptyState
                  icon={
                    <Lottie
                      options={{
                        loop: true,
                        autoplay: true,
                        animationData: NoFiltersAnimation,
                      }}
                      height={"120px"}
                      width={"120px"}
                    />
                  }
                  title={localization.you_have_no_filters}
                  subtitle={
                    localization.start_by_clicking_Add_Filter_to_add_your_first_filter
                  }
                />
              </div>
            )}
          </div>
        </CardContent>
      </Card>

      <Modal
        isOpen={isOpenDeleteFilterModal}
        onClose={() => setIsOpenDeleteFilterModal(false)}
        title={localization.delete_filter}
        modalActions={[
          {
            text: localization.delete,
            type: "button",
            isDestructive: true,
            isLoading: isDeletingFilteredPosts,
            onClickHandler: confirmDeleteFilter,
            disabled: isDeletingFilteredPosts,
          },
          {
            text: localization.cancel,
            variant: "secondary",
            type: "button",
            onClickHandler: () => setIsOpenDeleteFilterModal(false),
            disabled: isDeletingFilteredPosts,
          },
        ]}
      >
        <p className="manager-modalDescription">
          {localization.delete_filter_modal}
        </p>

        <div className="manager-modalDescription-Warning">
          <div className="manager-modalDescription-warningIcon">
            {WarningIcon}
          </div>
          <p className="manager-modalDescriptionWarningMessage">
            {localization.warning_delete_filter_modal}
          </p>
        </div>
      </Modal>

      <Modal
        isOpen={isOpenAddFilterModal}
        onClose={handleCloseFilterModal}
        title={localization.save_filter}
      >
        <form
          onSubmit={handleSubmit(handleSaveFilteredPosts)}
          className="manager-modalForm"
        >
          <Controller
            key="filter_name"
            name="filter_name"
            control={control}
            defaultValue={filterDetails.filter_name}
            rules={{
              required: localization.filter_name_required,
            }}
            render={({ field, fieldState }) => {
              return (
                <InputField
                  name={field.name}
                  label={localization.filter_name}
                  value={filterDetails.filter_name}
                  placeholder={localization.filter_name_placeholder}
                  onChange={(name, value) => {
                    handleFieldChange(value, field);
                  }}
                  errorMessage={fieldState.error?.message}
                />
              );
            }}
          />
          <div className="manager-textarea">
            <label>{localization.description}</label>
            <textarea
              id="manager-textarea"
              name="description"
              value={filterDetails.description}
              placeholder={localization.filter_description_placeholder}
              onChange={(e) => {
                handleInputChange(e.target.name, e.target.value);
              }}
              onFocus={(e) => {
                if (
                  e.target.value ===
                  localization.this_is_a_description_of_this_filter_please_edit_me
                ) {
                  handleInputChange(e.target.name, "");
                }
              }}
              onBlur={(e) => {
                if (e.target.value.trim() === "") {
                  handleInputChange(
                    e.target.name,
                    localization.this_is_a_description_of_this_filter_please_edit_me
                  );
                }
              }}
              rows={4}
              cols={40}
            />
          </div>
          <div className="manager-slugWrapper">
            {" "}
            <InputField
              name="slug"
              label={localization.page_slug}
              concatenatedString={
                homeURLs?.[filters.language || "default"] ??
                topPostsData.homeURL
              }
              description={localization.link_to_wordpress}
              value={filterDetails.slug}
              placeholder={localization.slug_placeholder}
              onChange={handleInputChange}
            />
            {userFilters[selectedFilter]?.page?.url &&
              !slugHasChanged() &&
              !langHasChanged() && (
                <div className="manager-linkButton">
                  <Tooltip text={localization.open_link}>
                    <Button
                      variant="secondary"
                      onClickHandler={() => {
                        window.open(
                          userFilters[selectedFilter]?.page?.url,
                          "_blank"
                        );
                      }}
                      icon={OpenNewPage}
                      shape="boxy"
                      size="lg"
                    />
                  </Tooltip>
                </div>
              )}
          </div>
          <div className="manager-modalActionButtons">
            <Button
              text={localization.save}
              type="submit"
              isLoading={isSavingFilteredPosts}
              disabled={isSavingFilteredPosts && isSavingFilterInfo}
            />
            <Button
              text={localization.cancel}
              variant="secondary"
              onClickHandler={handleCloseFilterModal}
              disabled={isSavingFilteredPosts}
            />
          </div>
        </form>
      </Modal>
    </div>
  );
};

export default TopPostsManager;
