"use client";
import ProductSkeleton from "@/components/ProductSkeleton";
import FilterSkeleton from "@/components/FilterSkeleton";
import { useState, useEffect, useRef, useMemo } from "react";
import { useAppSelector } from "@/app/store/hooks";
import { selectWishlistProductIds } from "@/app/store/slices/wishlistSlice";
import { IoChevronDownSharp } from "react-icons/io5";
import Link from "next/link";
import { IoIosArrowForward } from "react-icons/io";
import { RxCross2 } from "react-icons/rx";
import Button from "@/components/common/Button";
import { ArrowUpDown } from "lucide-react";
import { TbFilter } from "react-icons/tb";
import BottomDrawer from "@/components/BottomDrawerProps";
import { usePathname, useSearchParams } from "next/navigation";
import {
  fetchProductsWithFilters,
  fetchFiltersData,
} from "@/lib/actions/productFilterActions";
import { useFormatDateTime } from "@/lib/utils/dateTimeUtils";
import Pagination from "@/components/Pagination/Paginate";
import { getStoredLocale } from "@/lib/getLocale";
import { toast } from "react-toastify";
import Tree from "@/components/Filters/TreeComponent";
import { getStates } from "@/lib/actions/countryStateCityActions";
import { SERVICE_FORM_TYPE } from "@/lib/formTypes";
import BreadCrumb from "@/components/Breadcrumb";
import { useTranslations } from "next-intl";
import DataNotFound from "@/components/common/DataNotFound";
import RouteLoader from "@/components/common/RouteLoader";
import Loader from "@/components/common/Loader";

export interface Creator {
  first_name: string;
  last_name: string;
  email: string;
  profile_image: string;
  _id: string;
}

export interface Service {
  _id: string;
  title: string;
  description: string;
  createdAt: string;
  creator: Creator;
  image?: string | null;
}

function AllServicesPageContent() {
  const [sortOpen, setSortOpen] = useState(false);
  const [regionOpen, setRegionOpen] = useState(false);
  const wishlistItems = useAppSelector(selectWishlistProductIds);
  const user = useAppSelector((state) => state.auth.user);
  const sortRef = useRef<HTMLDivElement>(null);
  const regionRef = useRef<HTMLDivElement>(null);
  const [filterData, setFilterData] = useState<any | null>(null);
  const [filtersLoading, setFiltersLoading] = useState(false);
  const [filtersError, setFiltersError] = useState<string | null>(null);
  const [products, setProducts] = useState<any[]>([]);
  const [filterOptions, setFilterOptions] = useState<any>(null);
  const [pagination, setPagination] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [category, setCategory] = useState<string | null>(null);
  const [currentPage, setCurrentPage] = useState(1);
  const locale = getStoredLocale();
  const { formatDateTime } = useFormatDateTime();
  const pathName = usePathname();

  const createBaseFilterState = () => ({
    priceRange: [0, 0],
    selectedBrands: [],
    selectedAttributes: [],
    selectedColors: [],
    selectedConditions: [],
    selectedFuels: [],
    selectedStates: [],
    selectedTags: [],
  });

  const [appliedFilters, setAppliedFilters] = useState<any>();
  // createBaseFilterState()

  const [pendingFilters, setPendingFilters] = useState<any>(
    createBaseFilterState()
  );

  const [hasUserAdjustedPrice, setHasUserAdjustedPrice] = useState(false);

  const t = useTranslations();

  const searchParams = useSearchParams();

  const createDynamicFilterStateFromNewAPI = (filterData: any) => {
    const baseState: any = {
      priceRange: [0, 0],
      selectedBrands: [],
      selectedStates: [],
      selectedTags: [],
      selectedColors: [],
      selectedConditions: [],
      selectedFuels: [],
    };

    // Handle the new filter data structure (array of attributes)
    if (Array.isArray(filterData)) {
      filterData.forEach((attr: any) => {
        const { id, type, title } = attr;

        const key = attr?.label?.en.toLowerCase().replace(/ /g, "_");
        // Create filter key for dynamic attributes
        const filterKey = key;
        baseState[filterKey] = [];
      });
    }

    return baseState;
  };

  const [sortOption, setSortOption] = useState<string>("latest");

  const [treeData, setTreeData] = useState<any[] | null>(null);

  // URL and category management
  useEffect(() => {
    const categoryFromUrl = searchParams?.get("category");
    setCategory(categoryFromUrl || "fresh-recommendations");
    setInitialLoadComplete(false); // Reset when category changes
    isInitialLoad.current = true; // Reset initial load flag
  }, [searchParams]);

  // Data fetching effects
  useEffect(() => {
    if (category) {
      fetchInitialFilters();
    }
  }, [category]);

  // Track if initial load is complete to avoid duplicate calls
  const [initialLoadComplete, setInitialLoadComplete] = useState(false);
  const isInitialLoad = useRef(true);

  // Fetch products when page changes
  useEffect(() => {
    // if (filterData && initialLoadComplete) {
    //   fetchProducts();
    // }

    if (initialLoadComplete) {
      fetchProducts();
    }
  }, [currentPage, sortOption]);

  // Click outside handlers for dropdowns
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as Node;
      if (sortRef.current && !sortRef.current.contains(target)) {
        setSortOpen(false);
      }
      if (regionRef.current && !regionRef.current.contains(target)) {
        setRegionOpen(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  const transformServices = (data: any) => {
    const fetchedServices = data;

    const imageMap: Record<string, string> = {};
    if (Array.isArray(fetchedServices)) {
      fetchedServices.forEach((item: any) => {
        const imgAttr = item.attributes.find(
          (attr: any) => attr.type === "singleimageuploader"
        );
        if (imgAttr) {
          const imageLocation = imgAttr?.meta?.files?.[0]?.location;
          if (imageLocation) imageMap[item._id] = imageLocation;
        }
      });
    }

    const merged = fetchedServices.map((srv: any) => {
      // Extract only the needed values from attributes
      let title = "";
      let description = "";

      srv.attributes?.forEach((attr: any) => {
        const slug = attr.attributeSlug;
        const value = attr.value;

        switch (slug) {
          case "title":
            title = value;
            break;
          case "short-description":
            description = value;
            break;
        }
      });

      // Create the service object matching the simplified interface
      const service: Service = {
        _id: srv._id,
        title,
        description,
        createdAt: srv.createdAt,
        creator: srv.creator,
        image: imageMap[srv._id] || null,
      };

      return service;
    });

    setProducts(merged);
  };

  const fetchInitialFilters = async () => {
    if (!category) {
      return;
    }
    try {
      setFiltersLoading(true);
      setFiltersError(null);
      setLoading(true);
      setError(null);

      const currentCategory = category;

      const categorySlug = category;
      const parentCategory = SERVICE_FORM_TYPE;

      let payload: any = {
        categorySlug,
        parentCategory,
      };

      const filtersResponse = await fetchFiltersData(payload);

      if (categorySlug == "fresh-recommendations") {
        const data = filtersResponse.data?.categoryGetChildCategory;

        setTreeData(data);
        setFilterData(null);
      }

      // Fetch products separately
      const sellerId = searchParams?.get("sellerId") || null;
      const productsResponse = await fetchProductsWithFilters(
        {
          category: currentCategory as string,
          filters: undefined, // No filters applied
          page: 1,
          limit: 12,
          fetchAllFilters: false,
          sellerId: sellerId,
          slug: SERVICE_FORM_TYPE,
        } // fetchAllFilters = false, just get products
      );

      if (productsResponse.data.data) {
        const fetchedServices = productsResponse.data.data.services;

        transformServices(fetchedServices);
        setPagination(productsResponse.data.data.pagination);
        setCurrentPage(1);
      }
    } catch (err: any) {
      setFiltersError(err.message || t("failed_to_fetch_filter_data"));
      setError(err.message || t("failed_to_fetch_products"));
      setFilterData(null);
      setProducts([]);
      setPagination(null);
    } finally {
      setFiltersLoading(false);
      setLoading(false);
      setInitialLoadComplete(true);
      isInitialLoad.current = false; // Mark initial load as complete
    }
  };

  const fetchProducts = async (customFilters?: any) => {
    if (!category) {
      return;
    }
    try {
      setLoading(true);
      setError(null);

      // Use custom filters if provided, otherwise use current appliedFilters
      const filtersForAPI = customFilters
        ? { ...customFilters }
        : { ...appliedFilters };
      // Reset price range if user hasn't adjusted it
      if (!hasUserAdjustedPrice) {
        filtersForAPI.priceRange = [0, 0];
      }

      const currentCategory = category;
      const response = await fetchProductsWithFilters({
        category: currentCategory,
        filters: filtersForAPI, // Apply current filter selections
        page: currentPage,
        limit: 12,
        fetchAllFilters: false, // fetchAllFilters = false, just get products
        sort: sortOption,
        slug: SERVICE_FORM_TYPE,
      });

      transformServices(response?.data?.data?.services);
      setPagination(response.data.data.pagination);
    } catch (err: any) {
      setError(err.message || t("failed_to_fetch_products"));
      setProducts([]);
      setPagination(null);
      setFilterOptions(null);
    } finally {
      setLoading(false);
    }
  };

  const activeFilters = useMemo(() => {
    const filters: any[] = [];

    if (hasUserAdjustedPrice && appliedFilters?.priceRange) {
      filters.push({
        field: "priceRange",
        value: appliedFilters.priceRange,
        label: {
          en: `SAR ${appliedFilters.priceRange[0]} - SAR ${appliedFilters.priceRange[1]}`,
          ar: `SAR ${appliedFilters.priceRange[0]} - SAR ${appliedFilters.priceRange[1]}`,
        },
        type: "range",
      });
    }

    const staticMap: Record<
      string,
      { key: string; title: string; options?: any[] }
    > = {
      selectedColors: {
        key: "color",
        title: "Color",
        options: filterOptions?.colors,
      },
      selectedBrands: {
        key: "brand",
        title: "Brand",
        options: filterOptions?.brands,
      },
      selectedTags: {
        key: "tags",
        title: "Tags",
        options: filterOptions?.tags,
      },
      selectedConditions: {
        key: "condition",
        title: "Condition",
        options: filterOptions?.conditions,
      },
      selectedFuels: {
        key: "fuel",
        title: "Fuel",
        options: filterOptions?.fuels,
      },
    };

    Object.entries(staticMap).forEach(([filterKey, { key, options }]) => {
      const selected = appliedFilters?.[filterKey] || [];

      selected.forEach((selectedOpt: any) => {
        if (selectedOpt?.value) {
          filters.push(selectedOpt);
        } else {
          const opt = options?.find((o: any) => o.value === selectedOpt);
          if (opt) {
            filters.push(opt);
          } else {
            filters.push({
              field: key,
              value: String(selectedOpt),
              label: selectedOpt,
            });
          }
        }
      });
    });

    if (appliedFilters) {
      Object.entries(appliedFilters).forEach(
        ([attrKey, attrOptions]: [string, any]) => {
          if (attrKey == "priceRange" || staticMap[attrKey]) return;

          const selectedValues = appliedFilters[attrKey] || [];
          if (selectedValues.length > 0) {
            selectedValues.forEach((selectedOpt: any) => {
              // If already a full object, just push it
              if (selectedOpt?.value) {
                filters.push(selectedOpt);
              } else {
                // fallback: find option by value if only ID is stored
                const option = attrOptions.find(
                  (o: any) => o.value === selectedOpt
                );
                if (option) {
                  filters.push(option);
                } else {
                  filters.push({
                    field: attrKey,
                    value: String(selectedOpt),
                    label: selectedOpt,
                    meta: selectedOpt?.meta,
                  });
                }
              }
            });
          }
        }
      );
    }

    return filters;
  }, [appliedFilters, filterOptions, hasUserAdjustedPrice, filterData]);

  const removeFilter = (filter: string) => {
    let newFilters = { ...appliedFilters };
    if (Array.isArray(filter)) {
      // this is price remove
      newFilters["priceRange"] = [0, 0];

      setAppliedFilters(newFilters);
      return;
    }

    Object.keys(newFilters).forEach((key) => {
      const selected = newFilters[key] || [];

      newFilters[key] = selected.filter((opt: any) => opt.value !== filter);
    });

    setAppliedFilters(newFilters);

    if (initialLoadComplete && !isInitialLoad.current) {
      fetchProducts(newFilters);
    }
  };

  const applyMobileFilters = () => {
    setAppliedFilters(pendingFilters);
    setIsDrawerOpen(false);
    // Trigger product fetch when mobile filters are applied
    if (initialLoadComplete && !isInitialLoad.current) {
      fetchProducts(pendingFilters); // Pass the new filters directly
    }
  };

  const closeMobileDrawer = () => {
    setPendingFilters(appliedFilters); // Reset to original state
    setIsDrawerOpen(false);
  };

  const handlePageChange = (selectedItem: { selected: number }) => {
    const newPage = selectedItem.selected + 1;
    setCurrentPage(newPage);
  };

  const [isDrawerOpen, setIsDrawerOpen] = useState(false);
  const [isDrawerOpenSort, setIsDrawerOpenSort] = useState(false);

  const [activeSort, setActiveSort] = useState("recent");

  const options = [
    { label: t("recently_posted"), value: "latest" },
    { label: t("lowest_price"), value: "low_price" },
    { label: t("highest_price"), value: "high_price" },
  ];

  const [states, setStates] = useState<any>(null);

  const getStateDate = async (country_id: any) => {
    var isStateData = [];
    // setCities([]);
    try {
      const response = await getStates(user?.token, country_id);
      if (response.success && Array.isArray(response?.stateData)) {
        isStateData = response?.stateData.map((opt: any) => ({
          value: opt._id,
          label: opt.name,
        }));
      }
    } catch (error: any) {
      // if (checkAuthErrorGet(error, dispatch, router)) return;
      // toast.error(error?.response?.data?.message || t("validation.error_msg"));
    } finally {
      setStates(isStateData);
    }
  };

  useEffect(() => {
    getStateDate(process.env.NEXT_PUBLIC_COUNTRY_CODE);
  }, []);

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <Loader />
      </div>
    );
  }

  return (
    <RouteLoader>
      <div className="dark:bg-background">
        <section className="p-6">
          <div className="max-w-w1660 mx-auto relative">
            <div className="flex gap-6">
              {typeof window !== "undefined" && window.innerWidth >= 768 && (
                <div className="max-md:hidden">
                  {filtersLoading ? (
                    <FilterSkeleton />
                  ) : filtersError ? (
                    <div className="w-80 bg-neutrals50 rounded-lg dark:bg-card p-4">
                      <div className="text-center text-red-500 dark:text-red-400">
                        {t("error_loading_filters")}
                      </div>
                    </div>
                  ) : treeData ? (
                    <Tree
                      category={SERVICE_FORM_TYPE}
                      data={treeData}
                      language={locale == "en" ? "en" : "ar"}
                    />
                  ) : null}
                </div>
              )}
              <div className="flex-1">
                {/* Breadcrumb */}
                <BreadCrumb
                  items={[
                    { title: t("header.home"), href: "/" },
                    { title: SERVICE_FORM_TYPE, href: `/service` },
                  ]}
                />

                <div className="flex justify-between mb-2.5 pb-2.5 border-b gap-2 border-neutrals100 max-[1024px]:items-start dark:border-darkborder">
                  <div className="flex items-center flex-wrap gap-2.5 max-md:pt-2.5">
                    {/* Results and filters */}
                    <div className="text-sm text-neutrals900 font-semibold pr-2.5 border-r border-neutrals200 max-[1024px]:border-hidden dark:text-white dark:border-darkborder">
                      {!category ? (
                        <div className="h-4 bg-neutrals100 dark:bg-background rounded w-32 animate-pulse" />
                      ) : loading ? (
                        <div className="h-4 bg-neutrals100 dark:bg-background rounded w-24 animate-pulse" />
                      ) : (
                        <>
                          {pagination?.total || 0} {t("result_for")} {category}
                          {appliedFilters?.selectedStates.length > 0 ? (
                            <span> {t("in_selected_states")}</span>
                          ) : (
                            <span> {t("from_all_regions")}</span>
                          )}
                        </>
                      )}
                    </div>

                    {/* Active filters */}
                    {activeFilters.length > 0 && (
                      <div className="flex flex-wrap gap-2">
                        {activeFilters.map((filter: any, index: number) => {
                          const field = filter?.field
                            ? filter.field
                              .replace(/_/g, " ")
                              .charAt(0)
                              .toUpperCase() +
                            filter.field
                              .replace(/_/g, " ")
                              .slice(1)
                              .toLowerCase()
                            : undefined;

                          if (
                            !filter?.value ||
                            (filter.value.length === 2 &&
                              filter.value[0] == 0 &&
                              filter.value[1] == 0)
                          ) {
                            return null;
                          }

                          return (
                            <div
                              key={`${filter?.key}-${index}`}
                              className="bg-kzblue50 text-primary500 text-xs rounded-full flex items-center gap-1 py-1 px-2 dark:bg-card dark:text-primary400"
                            >
                              <span className="flex items-center gap-1 text-xs text-primary500 dark:text-primary400">
                                {field} {": "}{" "}
                                {filter?.label?.en
                                  ? filter?.label?.en
                                  : filter?.label}
                                {filter?.imageUrl && (
                                  <div
                                    className={`w-8 h-8 border-2 overflow-hidden transition-all duration-200 ${filter?.type?.includes("radio")
                                      ? "rounded-full"
                                      : "rounded"
                                      } `}
                                  >
                                    <img
                                      src={`${process.env.NEXT_PUBLIC_API}/${filter.imageUrl}`}
                                      alt={filter.label?.en || ""}
                                      className="w-full h-full object-cover"
                                      onError={(e) => {
                                        e.currentTarget.onerror = null;
                                        e.currentTarget.src =
                                          "/profile-avatar.png";
                                      }}
                                    />
                                  </div>
                                )}
                              </span>
                              <RxCross2
                                className="cursor-pointer text-sm ml-1"
                                onClick={() => removeFilter(filter?.value)}
                              />
                            </div>
                          );
                        })}
                      </div>
                    )}
                  </div>
                  <div className="flex items-center max-lg:flex-wrap-reverse max-lg:items-end max-lg:h-fit justify-end gap-2.5">
                    <div className="flex items-center gap-2.5">
                      <span className="text-sm font-normal text-neutrals400 whitespace-nowrap max-md:hidden">
                        {t("sort_by")}:
                      </span>
                      {/* Sort Dropdown */}
                      <div className="relative max-md:hidden" ref={sortRef}>
                        <button
                          onClick={() => {
                            setSortOpen(!sortOpen);
                            setRegionOpen(false);
                          }}
                          className="min-w-24 text-sm text-neutrals800 border px-3 py-3 pl-2 rounded-md flex items-center justify-between gap-1 max-[1024px]:py-2 dark:bg-card dark:text-neutrals400 dark:border-darkborder"
                        >
                          {
                            options?.find((obj) => obj.value === sortOption)
                              ?.label
                          }
                          <IoChevronDownSharp />
                        </button>
                        {sortOpen && (
                          <div className="absolute right-0 z-30 p-2 mt-2 bg-white border-neutrals200 border rounded-md shadow-md min-w-[177px] dark:bg-card dark:text-neutrals400 r dark:border-darkborder rtl:left-0 rtl:right-auto">
                            <ul className="text-sm text-neutrals800">
                              <li
                                className="px-4 py-2 rounded-md hover:bg-neutrals50 text-primary500 cursor-pointer dark:text-primary400 dark:hover:bg-background"
                                onClick={() => {
                                  setSortOption("latest");
                                  setSortOpen(!sortOpen);
                                }}
                              >
                                {t("recently_posted")}
                              </li>
                              <li
                                className="px-4 py-2 rounded-md hover:bg-neutrals50 text-primary500 cursor-pointer dark:text-primary400 dark:hover:bg-background"
                                onClick={() => {
                                  setSortOption("low_price");
                                  setSortOpen(!sortOpen);
                                }}
                              >
                                {t("lowest_price")}
                              </li>
                              <li
                                className="px-4 py-2 rounded-md hover:bg-neutrals50 text-primary500 cursor-pointer dark:text-primary400 dark:hover:bg-background"
                                onClick={() => {
                                  setSortOption("high_price");
                                  setSortOpen(!sortOpen);
                                }}
                              >
                                {t("highest_price")}
                              </li>
                            </ul>
                          </div>
                        )}
                      </div>

                      {/* Region Dropdown */}
                      {/* <div className="relative" ref={regionRef}>
                        <button
                          onClick={() => {
                            setRegionOpen(!regionOpen);
                            setSortOpen(false);
                          }}
                          className="min-w-24 text-sm text-neutrals800 border px-3 py-3 pl-2 rounded-md flex items-center justify-between gap-1 max-[1024px]:py-2 dark:bg-card dark:text-neutrals400 dark:border-darkborder"
                        >
                          Region
                          {appliedFilters?.selectedStates?.length > 0
                            ? ` (${appliedFilters?.selectedStates.length})`
                            : ""}
                          <IoChevronDownSharp />
                        </button>
                        {regionOpen && (
                          <div className="absolute right-0 z-30 p-2 mt-2 bg-white border-neutrals200 border rounded-md shadow-md min-w-[177px] dark:bg-card dark:text-neutrals400 r dark:border-darkborder rtl:left-0 rtl:right-auto overflow-auto h-[200px]">
                            <ul className="text-sm text-neutrals800">
                              {(() => {
                                if (!filterData) return null;
  
                                // const states: { value: string; label: string }[] =
                                //   [];
  
                                // Handle both new and old API structures
                                // if (Array.isArray(filterData)) {
                                //   // New API structure - look for state attributes
                                //   filterData.forEach((attr: any) => {
                                //     if (
                                //       attr.type ===
                                //         "singleselectdropdownwithsearch" &&
                                //       attr.title?.en
                                //         ?.toLowerCase()
                                //         .includes("state")
                                //     ) {
                                //       attr.options?.forEach((option: any) => {
                                //         const keyStr = option._id.toString();
                                //         if (!seenKeys.has(keyStr)) {
                                //           seenKeys.add(keyStr);
                                //           states.push({
                                //             key: keyStr,
                                //             value:
                                //               option.value?.en ||
                                //               option.value ||
                                //               option._id,
                                //           });
                                //         }
                                //       });
                                //     }
                                //   });
                                // } else if (filterData.regions?.states) {
                                //   // Old API structure
                                //   filterData.regions.states.forEach(
                                //     (stateItem: any) => {
                                //       let state;
  
                                //       // Check if it's already an object (new format) or a JSON string (old format)
                                //       if (
                                //         typeof stateItem === "object" &&
                                //         stateItem.key &&
                                //         stateItem.value
                                //       ) {
                                //         state = stateItem;
                                //       } else {
                                //         try {
                                //           state = JSON.parse(stateItem);
                                //         } catch {
                                //           return; // Skip invalid entries
                                //         }
                                //       }
  
                                //       if (state.key && state.value) {
                                //         const keyStr = state.key.toString();
                                //         // Only add if we haven't seen this key before
                                //         if (!seenKeys.has(keyStr)) {
                                //           seenKeys.add(keyStr);
                                //           states.push({
                                //             key: keyStr,
                                //             value: state.value,
                                //           });
                                //         }
                                //       }
                                //     }
                                //   );
                                // }
  
                                if (states.length === 0) {
                                  return (
                                    <li className="px-4 py-2 text-neutrals500 dark:text-neutrals400">
                                      No states available
                                    </li>
                                  );
                                }
  
                                return states.map(
                                  (state: { value: string; label: string }) => (
                                    <li
                                      key={state.value}
                                      className="px-4 py-2 rounded-md hover:bg-neutrals50 text-primary500 cursor-pointer dark:text-primary400 dark:hover:bg-background"
                                      onClick={() => {
                                        const hasObj =
                                          appliedFilters.selectedStates?.find(
                                            (obj: any) =>
                                              obj.value === state.value
                                          );
                                        let newStates = [];
                                        if (hasObj) {
                                          newStates =
                                            appliedFilters?.selectedStates.filter(
                                              (s: any) => s.value !== state.value
                                            );
                                        } else {
                                          newStates = [
                                            { ...state, field: "state" },
                                          ];
                                        }
  
                                        const newFilters = {
                                          ...appliedFilters,
                                          selectedStates: newStates,
                                        };
  
                                        setAppliedFilters(newFilters);
  
                                        setRegionOpen(false);
                                        if (
                                          initialLoadComplete &&
                                          !isInitialLoad.current
                                        ) {
                                          fetchProducts(newFilters);
                                        }
                                      }}
                                    >
                                      {state.label}
                                      {appliedFilters?.selectedStates.includes(
                                        state.label
                                      ) && (
                                        <span className="ml-2 text-xs">✓</span>
                                      )}
                                    </li>
                                  )
                                );
                              })()}
                            </ul>
                          </div>
                        )}
                      </div> */}
                    </div>
                  </div>
                </div>

                {!category ? (
                  <ProductSkeleton count={12} isGrid={true} />
                ) : // ) : loading || !filterData ? (
                  loading ? (
                    <ProductSkeleton count={12} isGrid={true} />
                  ) : error ? (
                    <div className="flex flex-col justify-center items-center py-10 gap-4">
                      <div className="text-red-500 text-center">{error}</div>
                      <div className="text-sm text-neutrals500 dark:text-neutrals400 text-center max-w-md">
                        {error.includes("Network error")
                          ? "Please check your internet connection and ensure the API server is running."
                          : "There was an issue loading the products. Please try again later."}
                      </div>
                      <button
                        onClick={() => fetchProducts()}
                        className="px-4 py-2 bg-primary500 text-white rounded-lg hover:bg-primary600 dark:bg-primary400 dark:hover:bg-primary500"
                      >
                        {t("retry")}
                      </button>
                    </div>
                  ) : products.length > 0 ? (
                    <>
                      <div className="grid gap-4 grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-2 xl:grid-cols-4 2xl:grid-cols-5">
                        {products.map((service: Service) => (
                          <Link
                            key={service?._id}
                            href={`/service/${service?._id}`}
                          >
                            <div className="flex-shrink-0 overflow-hidden relative border border-neutrals100 rounded-lg bg-white dark:bg-card dark:border-card">
                              {service?.image && (
                                <img
                                  src={`${process.env.NEXT_PUBLIC_API}/${service?.image}`}
                                  alt={service?.title}
                                  className="w-full h-40 object-cover"
                                  onError={(e) => {
                                    e.currentTarget.onerror = null;
                                    e.currentTarget.src = "/default.jpg";
                                  }}
                                />
                              )}
                              <div className="p-4 pb-4">
                                <div className="flex justify-between items-center mb-5">
                                  <div className="flex items-center gap-2">
                                    <img
                                      src={`${process.env.NEXT_PUBLIC_IMAGE_BASE_URL}/${service?.creator?.profile_image}`}
                                      alt={service?.creator?.first_name}
                                      className="w-8 h-8 rounded-full object-cover"
                                      onError={(e) => {
                                        e.currentTarget.onerror = null;
                                        e.currentTarget.src =
                                          "/profile-avatar.png";
                                      }}
                                    />
                                    <p className="text-sm font-semibold text-primary500 dark:text-white">
                                      {service?.creator?.first_name}{" "}
                                      {service?.creator?.last_name}
                                    </p>
                                  </div>
                                </div>
                                <p className="text-sm text-neutrals500 line-clamp-3">
                                  {service?.description}
                                </p>
                              </div>
                              <div className="flex items-center justify-between bg-neutrals50 text-xs py-2 px-4 text-neutrals500 dark:bg-cardfooter">
                                <div className="flex items-center gap-1">
                                  <span className="text-sm text-neutrals800 dark:text-neutrals400">
                                    {/* {service?.cityOrState} */}
                                  </span>
                                </div>
                                <span className="text-sm text-neutrals800 dark:text-neutrals400">
                                  {formatDateTime(service?.createdAt)}
                                </span>
                              </div>
                            </div>
                          </Link>
                        ))}
                      </div>

                      {/* Pagination */}
                      {pagination && pagination.totalPages > 1 && (
                        <div className="mt-6">
                          <Pagination
                            pageCount={pagination.totalPages}
                            currentPage={currentPage}
                            onPageChange={handlePageChange}
                          />
                        </div>
                      )}
                    </>
                  ) : (
                    <DataNotFound />
                  )}
              </div>
            </div>
          </div>
        </section>

        <div className="hidden max-md:block">
          {/* Filter Drawer */}
          <BottomDrawer
            isOpen={isDrawerOpen}
            title={t("filters1")}
            onClose={closeMobileDrawer}
            footer={
              <div className="flex justify-end gap-2">
                <Button
                  type="button"
                  label={t("apply")}
                  variant="secondary"
                  className="w-full flex justify-center items-center"
                  onClick={applyMobileFilters}
                />
              </div>
            }
          >
            {filtersLoading ? (
              <div className="p-4">
                <FilterSkeleton />
              </div>
            ) : (
              treeData && (
                <Tree
                  category={SERVICE_FORM_TYPE}
                  data={treeData}
                  language={locale == "en" ? "en" : "ar"}
                />
              )
            )}
          </BottomDrawer>

          {/* Sort Drawer */}
          <BottomDrawer
            isOpen={isDrawerOpenSort}
            title={t("sort")}
            onClose={() => setIsDrawerOpenSort(false)}
            footer={
              <div className="flex justify-end gap-2">
                <Button
                  type="submit"
                  label={t("apply")}
                  variant="secondary"
                  onClick={() => setIsDrawerOpenSort(false)}
                  className="w-full flex justify-center items-center"
                />
              </div>
            }
          >
            <div>
              {options.map((option, index) => (
                <div
                  key={option.value}
                  className={`px-4 py-3 cursor-pointer text-sm ${sortOption === option.value
                    ? "bg-neutrals50 text-primary500 rounded-lg dark:bg-card dark:text-primary400"
                    : "text-neutrals800 dark:text-neutrals400"
                    } ${index !== 0 &&
                    "border-t border-gray-100 dark:border-darkborder"
                    }`}
                  onClick={() => setSortOption(option.value)}
                >
                  {option.label}
                </div>
              ))}
            </div>
          </BottomDrawer>
        </div>
      </div>
    </RouteLoader>
  );
}

export default function AllServicesPage() {
  return <AllServicesPageContent />;
}
