// MainFilterContainer.tsx
"use client";

import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { RootState, AppDispatch } from "../../../../store";
import {
  categoryApiCall,
  searchListing,
  stateLocation,
} from "../../../../api/api";
import { setLocation } from "../../../../slice/LocationSlice";
import { useSearchParams } from "next/navigation";
import FilterSection from "./FilterSection";
import LocationModal from "./LocationModal";
import MobileFilterDialog from "./MobileFilterDialog";
import {
  loadLocationFromStorage,
  saveLocationToStorage,
} from "../../../../utils/locationUtils";

export default function MainFilterContainer() {
  const dispatch: AppDispatch = useDispatch();
  const searchParams = useSearchParams();
  const keyword = searchParams.get("keyword") || "";
  const [mobileFiltersOpen, setMobileFiltersOpen] = useState(false);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [selectedCountry, setSelectedCountry] = useState<any>();
  const [hasUserUpdatedFilters, setHasUserUpdatedFilters] = useState(false);
  const [selectedState, setSelectedState] = useState<string | null>(null);
  const [selectedLat, setSelectedLat] = useState<string | null>(null);
  const [selectedLong, setSelectedLong] = useState<string | null>(null);
  const [filtersState, setFiltersState] = useState({
    category_id: [] as number[],
    location: undefined as string | undefined,
    starting_price: undefined as number | undefined,
    ending_price: undefined as number | undefined,
    ad_type: undefined as string | undefined,
    fuel_type: undefined as string | undefined,
  });

  // Redux state selectors
  const { categories } = useSelector(
    (state: RootState) => state.CategoryListing
  );
  const searchListState = useSelector(
    (state: RootState) => state.searchReducer
  );
  const { stateLocationData, loadings } = useSelector(
    (state: RootState) => state.StateLocationReducer
  );
  // Get location from Redux
  const location = useSelector((state: RootState) => state.locationReducer);
  const { userData } = useSelector((state: RootState) => state.loginReducer);
  const CurrentUserID = userData?.data?.user?.id;

  // For loading location
  useEffect(() => {
    const savedLocation = loadLocationFromStorage();
    if (savedLocation) {
      dispatch(setLocation(savedLocation));
      setSelectedCountry(savedLocation.country);
      setSelectedState(savedLocation.state);
    }
  }, [dispatch]);

  // For saving location
  useEffect(() => {
    if (
      location.latitude &&
      location.longitude &&
      location.state &&
      location.country
    ) {
      saveLocationToStorage(location);
    }
  }, [location]);

  useEffect(() => {
    handleSearch(undefined, undefined, location?.country, location?.state);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [location, keyword]);

  useEffect(() => {
    dispatch(categoryApiCall());
  }, [dispatch]);

  useEffect(() => {
    setFiltersState({
      category_id: [],
      location: undefined,
      starting_price: undefined,
      ending_price: undefined,
      ad_type: undefined,
      fuel_type: undefined,
    });
    setHasUserUpdatedFilters(false);
  }, [keyword]);

  useEffect(() => {
    if (!hasUserUpdatedFilters && searchListState?.searchList?.data?.listings) {
      const selectedCategories = searchListState.searchList.data.listings
        .map((listing: any) => listing.category_id)
        .filter(
          (category_id: number, index: number, self: number[]) =>
            self.indexOf(category_id) === index
        );
      setFiltersState((prevState) => ({
        ...prevState,
        category_id: selectedCategories,
      }));
    }
  }, [searchListState?.searchList?.data?.listings, hasUserUpdatedFilters]);

  // Modify the handleFilterSubmit function for location
  const handleFilterSubmit = async (
    filterKey: keyof typeof filtersState,
    value: any
  ) => {
    setHasUserUpdatedFilters(true);
    console.log("filter ki value", filterKey);

    if (filterKey === "location") {
      // Always open modal when clicking location checkbox
      if (value === "US" || value === "CAN") {
        setSelectedLat(null);
        setSelectedLong(null);
        dispatch(stateLocation(value));
        setSelectedCountry(value);
        setIsModalOpen(true);
      }
      return;
    }

    // Rest of your existing logic for other filters...
    let updatedValue;

    if (Array.isArray(filtersState[filterKey])) {
      if ((filtersState[filterKey] as any[]).includes(value)) {
        updatedValue = (filtersState[filterKey] as any[]).filter(
          (item) => item !== value
        );
      } else {
        updatedValue = [...(filtersState[filterKey] as any[]), value];
      }
    } else {
      updatedValue = value;
    }

    if (Array.isArray(updatedValue)) {
      updatedValue = updatedValue.filter((item) => item != null);
    }

    const updatedFilters = {
      ...filtersState,
      [filterKey]: updatedValue,
    };

    setFiltersState(updatedFilters);
    console.log("state", selectedState, "country", selectedCountry);
    try {
      const finalFilters = {
        keyword: keyword,
        ...updatedFilters,
        ...(selectedLat && selectedLong
          ? {
              location_latitude: selectedLat,
              location_longitude: selectedLong,
            }
          : {}),
        ...{
          location: selectedCountry
            ? selectedCountry == "CAN"
              ? "Canada"
              : "USA"
            : "",
        },
        ...{
          sub_location:
            selectedState == "Canada" || selectedState == "USA"
              ? ""
              : selectedState,
        },
      };

      await dispatch(searchListing(finalFilters)).unwrap();
    } catch {
      return null;
    }
  };

  const handleSearch = async (
    latitude?: number,
    longitude?: number,
    selectedCountryValue?: string,
    stateValue?: string
  ) => {
    console.log(
      "latitude",
      latitude,
      "longitude",
      longitude,
      "selectedCountryValue",
      selectedCountryValue,
      "stateValue",
      stateValue,
      "selectedCountry",
      selectedCountry
    );

    // if (!selectedCountryValue && !selectedCountry) return;

    try {
      const params = {
        page: 1,
        user_id: CurrentUserID,
        location_latitude: String(latitude) || "",
        location_longitude: String(longitude) || "",
        location: selectedCountryValue
          ? selectedCountryValue == "CAN"
            ? "Canada"
            : "USA"
          : selectedCountry == "CAN"
          ? "Canada"
          : "USA",
        sub_location: stateValue
          ? stateValue == "USA" || stateValue == "Canada"
            ? ""
            : stateValue
          : location?.state || "",
        keyword: keyword,
        ...filtersState, // Include all filters from filtersState

        ...{
          location:
            (selectedCountryValue || selectedCountry) === "CAN"
              ? "Canada"
              : (selectedCountryValue || selectedCountry) === "US"
              ? "USA"
              : "",
        },
      };
      await dispatch(searchListing(params)).unwrap();
    } catch {
      return null;
    }
  };

  const handleStateChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const [state, lat, long] = event.target.value.split(",");
    setSelectedLat(lat);
    setSelectedLong(long);

    if (state === "All") {
      const fullState = selectedCountry === "CAN" ? "Canada" : "USA";
      setSelectedState(fullState);
      dispatch(
        setLocation({
          latitude: lat,
          longitude: long,
          state: fullState,
          country: selectedCountry,
        })
      );
      handleSearch(Number(lat), Number(long), selectedCountry, fullState);
      setIsModalOpen(false);
      return;
    }

    setSelectedState(state);
    dispatch(
      setLocation({
        latitude: lat,
        longitude: long,
        state,
        country: selectedCountry,
      })
    );
    handleSearch(Number(lat), Number(long), selectedCountry, state);
    setIsModalOpen(false);
  };

  useEffect(() => {
    if (location?.state) {
      setSelectedState(location.state);
      if (location.country) {
        setSelectedCountry(location.country);
      }
    }
  }, [location?.state, location?.country]);
  const filters = [
    {
      id: "category_id",
      name: "Category",
      options:
        categories?.data?.map((category: any) => ({
          value: category.id,
          label: category.name,
          checked: filtersState.category_id.includes(category.id),
        })) || [],
    },

    {
      id: "location",
      name: "Location",
      options: [
        {
          value: "US",
          label: "USA",
          checked: location?.country === "US", // Simplified check
        },
        {
          value: "CAN",
          label: "Canada",
          checked: location?.country === "CAN", // Simplified check
        },
      ],
    },
    {
      id: "fuel_type",
      name: "Fuel Type",
      options: [
        {
          value: "Gas",
          label: "Gas",
          checked: filtersState.fuel_type === "Gas",
        },
        {
          value: "Diesel",
          label: "Diesel",
          checked: filtersState.fuel_type === "Diesel",
        },
        {
          value: "Electric",
          label: "Electric",
          checked: filtersState.fuel_type === "Electric",
        },
        {
          value: "Hybrid electric",
          label: "Hybrid Electric",
          checked: filtersState.fuel_type === "Hybrid electric",
        },
      ],
    },
    {
      id: "ad_type",
      name: "Offer Type",
      options: [
        {
          value: "owner",
          label: "Owner",
          checked: filtersState.ad_type === "owner",
        },
        {
          value: "business",
          label: "Business",
          checked: filtersState.ad_type === "business",
        },
      ],
    },
  ];

  return (
    <div className="font-system">
      <MobileFilterDialog
        filters={filters}
        mobileFiltersOpen={mobileFiltersOpen}
        setMobileFiltersOpen={setMobileFiltersOpen}
        handleFilterSubmit={handleFilterSubmit}
      />

      {/* Desktop filter */}
      <main className="hidden lg:block xs:px-6 md:px-0 bg-[#F8F9F9]">
        <section
          aria-labelledby="products-heading"
          className="lg:pb-24 lg:pt-6"
        >
          <div className="flex items-center justify-between md:mb-3">
            <div className="md:h-14 lg:w-full xs:p-3 text-start rounded-lg bg-white flex md:pl-11 items-center">
              <p className="md:text-xl xs:text-sm font-bold text-[#3D3D3D]">
                Filter
              </p>
            </div>
          </div>
          <div className="lg:w-full">
            <form className="hidden lg:block bg-white p-5">
              {filters.map((section) => (
                <FilterSection
                  key={section.id}
                  section={section}
                  handleFilterSubmit={handleFilterSubmit}
                />
              ))}
            </form>
          </div>
        </section>
      </main>

      <LocationModal
        isOpen={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        selectedCountry={selectedCountry}
        selectedState={selectedState}
        stateLocationData={stateLocationData}
        loadings={loadings}
        handleStateChange={handleStateChange}
        // resetLocationSelection={() => {
        //   setFiltersState((prev) => ({
        //     ...prev,
        //     location: undefined,
        //   }));
        // }}
      />
    </div>
  );
}
