"use client";

import { useEffect, useState } from "react";
import {
  Dialog,
  DialogPanel,
  Disclosure,
  DisclosureButton,
  DisclosurePanel,
  Transition,
  TransitionChild,
} from "@headlessui/react";
import { XMarkIcon } from "@heroicons/react/24/outline";
import { useDispatch, useSelector } from "react-redux";
import { RootState, AppDispatch } from "../../../../store";
import {
  categoryApiCall,
  searchListing,
  stateLocation,
} from "../../../../api/api";
import { FunnelIcon } from "@heroicons/react/20/solid";
import filterSvg from "../../../../assets/filters.svg";
import filledarrow from "../../../../assets/filledarrow.svg";
import Modal from "../../../bayerProfile/pages/components/modal";
import { setLocation } from "../../../../slice/LocationSlice";
import { useSearchParams } from "next/navigation";
import Image from "next/image";

export default function Filter() {
  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,
  });
  const closeModal = () => setIsModalOpen(false);

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

  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]);

  const handleFilterSubmit = async (
    filterKey: keyof typeof filtersState,
    value: any
  ) => {
    setHasUserUpdatedFilters(true);
    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);

    if ((filterKey === "location" && value === "US") || value === "CAN") {
      setSelectedLat(null);
      setSelectedLong(null);
      dispatch(stateLocation(value));
      const country = value === "US" ? "US" : "CAN";
      setSelectedCountry(country);
      setIsModalOpen(true);
      return;
    }

    try {
      const finalFilters = {
        keyword: keyword,
        ...updatedFilters,
        ...(selectedLat && selectedLong
          ? {
              location_latitude: selectedLat,
              location_longitude: selectedLong,
            }
          : {}),
      };
      const actionResult = await dispatch(searchListing(finalFilters)).unwrap();

      if (actionResult?.data?.listings?.length > 0) {
        console.log(
          "Listings fetched successfully:",
          actionResult.data.listings
        );
      } else {
        console.log("No listings found");
      }
    } catch {
      // console.error("Search failed:", err);
      return null;
    }
  };

  const handleSearch = async (latitude: number, longitude: number) => {
    if (!latitude || !longitude) {
      // console.error("Latitude and longitude are required.");
      return;
    }

    try {
      const params = {
        page: 1,
        user_id: CurrentUserID,
        location_latitude: String(latitude),
        location_longitude: String(longitude),
        location: selectedCountry,
        keyword: keyword,
      };

      const result = await dispatch(searchListing(params)).unwrap();
      console.log("Location search successful:", result);
    } catch {
      // console.error("Search failed:", err);
      return null;
    }
  };

  const handleStateChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const [state, lat, long] = event.target.value.split(",");
    console.log("values------------------", state, lat, long, selectedCountry);
    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));
      setIsModalOpen(false);
      return;
    }

    setSelectedState(state);

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

  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: filtersState.location === "US" },
        {
          value: "CAN",
          label: "Canada",
          checked: filtersState.location === "CAN",
        },
      ],
    },
    {
      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">
      {/* Mobile filter dialog */}
      <div className="lg:hidden block">
        <button
          className="flex gap-2 items-center text-lg"
          type="button"
          onClick={() => setMobileFiltersOpen(true)}
        >
          Filter{" "}
          <Image
            unoptimized
            src={filterSvg}
            alt="Filter icon"
            width={20}
            height={20}
            className="w-5 h-5" // Tailwind or your custom class
          />
        </button>
        <Transition show={mobileFiltersOpen}>
          <Dialog className="relative z-40" onClose={setMobileFiltersOpen}>
            <TransitionChild
              enter="transition-opacity ease-linear duration-300"
              enterFrom="opacity-0"
              enterTo="opacity-100"
              leave="transition-opacity ease-linear duration-300"
              leaveFrom="opacity-100"
              leaveTo="opacity-0"
            >
              <div className="fixed inset-0 bg-black bg-opacity-25" />
            </TransitionChild>

            <div className="fixed inset-0 z-40 flex font-system">
              <TransitionChild
                enter="transition ease-in-out duration-300 transform"
                enterFrom="translate-x-full"
                enterTo="translate-x-0"
                leave="transition ease-in-out duration-300 transform"
                leaveFrom="translate-x-0"
                leaveTo="translate-x-full"
              >
                <DialogPanel className="relative ml-auto flex h-full w-full max-w-xs flex-col overflow-y-auto bg-white py-4 pb-12 shadow-xl">
                  <div className="flex items-center justify-between px-4">
                    <button
                      type="button"
                      className="-mr-2 flex h-10 w-10 items-center justify-center rounded-md bg-white p-2 text-gray-400"
                      onClick={() => setMobileFiltersOpen(false)}
                    >
                      <XMarkIcon className="h-6 w-6" aria-hidden="true" />
                    </button>
                  </div>

                  <form className="mt-4 border-t border-gray-200">
                    {filters.map((section) => (
                      <Disclosure
                        as="div"
                        key={section.id}
                        className="border-t border-gray-200 px-4 py-6"
                      >
                        {({ open }) => (
                          <>
                            <h3 className="-mx-2 -my-3 flow-root">
                              <DisclosureButton className="flex w-full items-center justify-between bg-white px-2 py-3 text-gray-400 hover:text-gray-500">
                                <span className="font-medium text-gray-900">
                                  {section.name}
                                </span>
                                <span className="ml-6 flex items-center">
                                  <Image
                                    unoptimized
                                    src={filledarrow}
                                    alt="Arrow icon"
                                    width={12} // corresponds to Tailwind h-3 (0.75rem = 12px)
                                    height={12} // corresponds to Tailwind w-3 (0.75rem = 12px)
                                    className={`transform ${
                                      open ? "rotate-180" : ""
                                    }`}
                                    aria-hidden="true"
                                  />
                                </span>
                              </DisclosureButton>
                            </h3>
                            <DisclosurePanel className="pt-6">
                              <div className="space-y-4">
                                {section.options.map(
                                  (option: any, optionIdx: any) => (
                                    <div
                                      key={option.value}
                                      className="flex items-center"
                                    >
                                      <input
                                        id={`filter-${section.id}-${optionIdx}`}
                                        name={`${section.id}[]`}
                                        value={option.value}
                                        type="checkbox"
                                        checked={option.checked}
                                        className="h-4 w-4 rounded border-gray-300 text-indigo-600 focus:ring-indigo-500"
                                        onChange={() =>
                                          handleFilterSubmit(
                                            section.id as keyof typeof filtersState,
                                            option.value
                                          )
                                        }
                                      />
                                      <label
                                        htmlFor={`filter-${section.id}-${optionIdx}`}
                                        className="ml-3 text-sm text-gray-600"
                                      >
                                        {option.label}
                                      </label>
                                    </div>
                                  )
                                )}
                              </div>
                            </DisclosurePanel>
                          </>
                        )}
                      </Disclosure>
                    ))}
                  </form>
                </DialogPanel>
              </TransitionChild>
            </div>
          </Dialog>
        </Transition>
      </div>

      {/* 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 className="flex items-center">
              <button
                type="button"
                className="-m-2 ml-4 p-2 text-gray-400 hover:text-gray-500 sm:ml-6 lg:hidden"
                onClick={() => setMobileFiltersOpen(true)}
              >
                <FunnelIcon className="h-5 w-5" aria-hidden="true" />
              </button>
            </div>
          </div>
          <div className="lg:w-full">
            <form className="hidden lg:block bg-white p-5">
              {filters.map((section) => (
                <Disclosure
                  as="div"
                  key={section.id}
                  className="border-b border-gray-200 py-4"
                >
                  {({ open }) => (
                    <>
                      <h3 className="-my-3 flow-root">
                        <DisclosureButton className="flex w-full items-center justify-between bg-white py-3 text-sm text-gray-400 hover:text-gray-500">
                          <span className="font-medium text-gray-900">
                            {section.name}
                          </span>
                          <span className="ml-6 flex items-center">
                            <Image
                              unoptimized
                              src={filledarrow}
                              width={12}
                              height={12}
                              alt="Arrow icon"
                              className={`transform ${
                                open ? "rotate-180" : ""
                              }`}
                            />
                          </span>
                        </DisclosureButton>
                      </h3>
                      <DisclosurePanel className="pt-6">
                        <div className="space-y-4">
                          {section.options.map(
                            (option: any, optionIdx: any) => (
                              <div
                                key={option.value}
                                className="flex items-center"
                              >
                                <input
                                  id={`filter-${section.id}-${optionIdx}`}
                                  name={`${section.id}[]`}
                                  value={option.value}
                                  type="checkbox"
                                  checked={option.checked}
                                  className="h-4 w-4 rounded border-gray-300 text-indigo-600 focus:ring-indigo-500"
                                  onChange={() =>
                                    handleFilterSubmit(
                                      section.id as keyof typeof filtersState,
                                      option.value
                                    )
                                  }
                                />
                                <div></div>

                                <label
                                  htmlFor={`filter-${section.id}-${optionIdx}`}
                                  className="ml-3 text-sm text-gray-600"
                                >
                                  {option.label}
                                </label>
                              </div>
                            )
                          )}
                        </div>
                      </DisclosurePanel>
                    </>
                  )}
                </Disclosure>
              ))}
            </form>
          </div>
        </section>
      </main>

      <Modal
        isOpen={isModalOpen}
        onClose={closeModal}
        title={`Select a Location`}
      >
        {loadings ? (
          <p className="text-black">Loading...</p>
        ) : (
          <form>
            <div className="grid grid-cols-2 gap-4 text-black">
              {/* Add "All" option manually */}
              <label className="flex items-center space-x-2">
                <input
                  type="radio"
                  name="state"
                  value={`All,${
                    selectedCountry === "USA"
                      ? "38.7946,106.5348"
                      : "56.1304,106.3468"
                  }`}
                  checked={
                    selectedCountry === "CAN"
                      ? selectedState === "Canada"
                      : selectedState === "USA"
                  }
                  onChange={handleStateChange}
                  className="form-radio"
                />
                <span className="text-black text-start">
                  All of {selectedCountry === "CAN" ? "Canada" : "USA"}
                </span>
              </label>
              {stateLocationData?.data?.list.map((state: any) => (
                <label
                  key={state.code}
                  className="flex items-center space-x-2 cursor-pointer"
                >
                  <input
                    type="radio"
                    name="state"
                    value={`${state.name},${state.latitude},${state.longitude}`}
                    checked={selectedState === state.name}
                    onChange={handleStateChange}
                    className="form-radio cursor-pointer"
                  />
                  <span className="text-black text-start cursor-pointer">
                    {state.name}
                  </span>
                </label>
              ))}
            </div>
          </form>
        )}

        {/* <button
          onClick={closeModal}
          className="mt-4 px-4 py-1 bg-yellow-500 cursor-pointer text-black rounded "
        >
          Close Modal
        </button> */}
      </Modal>
    </div>
  );
}
