"use client";
import { useRouter } from "next/navigation";
import { useState, useMemo } from "react";
import Select, { SingleValue, StylesConfig } from "react-select";

// Import useRouter for Next.js routing

import BlackBtn from "../../atoms/BlackButton";
import LocationsDataFetcher from "@/utils/locationDatafetcher";

import "./advance-filter.css";

interface SelectOption {
  value: string;
  label: string;
}

const AdvanceFilterBar = () => {
  const locationsData = LocationsDataFetcher({
    activeProjectLocations: [],
  }) as Array<{ attributes: { name: string } }>;
  const [searchFormData, setSearchFormData] = useState({
    location: "All",
    type: "Residential",
    size: {
      min: null as string | null,
      max: null as string | null,
    },
  });

  const router = useRouter();

  // Custom styles for react-select - memoized to prevent re-creation on every render
  const customStyles: StylesConfig<SelectOption, false> = useMemo(
    () => ({
      control: (provided) => ({
        ...provided,
        minHeight: "auto",
        height: "auto",
        border: "none",
        boxShadow: "none",
        backgroundColor: "transparent",
        cursor: "pointer",
        "&:hover": {
          border: "none",
        },
      }),
      valueContainer: (provided) => ({
        ...provided,
        padding: "0",
        fontFamily: "CreatoDisplay, sans-serif",
        fontSize: "14px",
        fontWeight: "normal",
        color: "#1F2937",
        lineHeight: "1",
      }),
      input: (provided) => ({
        ...provided,
        margin: "0",
        padding: "0",
        fontFamily: "CreatoDisplay, sans-serif",
        fontSize: "14px",
        fontWeight: "normal",
        color: "#1F2937",
      }),
      placeholder: (provided) => ({
        ...provided,
        margin: "0",
        fontFamily: "CreatoDisplay, sans-serif",
        fontSize: "14px",
        fontWeight: "normal",
        color: "#1F2937",
      }),
      singleValue: (provided) => ({
        ...provided,
        margin: "0",
        fontFamily: "CreatoDisplay, sans-serif",
        fontSize: "14px",
        fontWeight: "normal",
        color: "#1F2937",
      }),
      indicatorSeparator: () => ({
        display: "none",
      }),
      dropdownIndicator: (provided) => ({
        ...provided,
        padding: "0",
        color: "#1F2937",
        "&:hover": {
          color: "#1F2937",
        },
      }),
      menu: (provided) => ({
        ...provided,
        backgroundColor: "#F9FAFB",
        border: "1px solid #E5E7EB",
        borderRadius: "4px",
        boxShadow: "0 4px 6px -1px rgba(0, 0, 0, 0.1)",
        marginTop: "4px",
        zIndex: 9999,
        position: "absolute",
      }),
      menuList: (provided) => ({
        ...provided,
        padding: "0",
        maxHeight: "200px",
      }),
      option: (provided, state) => ({
        ...provided,
        backgroundColor: state.isSelected
          ? "#E5E7EB"
          : state.isFocused
          ? "#F3F4F6"
          : "#F9FAFB",
        color: "#1F2937",
        fontFamily: "CreatoDisplay, sans-serif",
        fontSize: "14px",
        fontWeight: "normal",
        padding: "8px 12px",
        cursor: "pointer",
        "&:hover": {
          backgroundColor: "#F3F4F6",
        },
      }),
    }),
    []
  );

  const handleChange = (name: string, value: string) => {
    if (name === "size") {
      const [min, max] = value.split(" - ");
      setSearchFormData((prevData) => ({ ...prevData, [name]: { min, max } }));
    } else {
      setSearchFormData((prevData) => ({ ...prevData, [name]: value }));
    }
  };

  const handleSearch = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const { location, type, size } = searchFormData;
    // const queryString = `?location=${location}&type=${type}&size=${JSON.stringify(size)}`;
    const queryString = `?location=${location}${
      !size.min ? "" : "&sizeMin=" + size.min
    }${!size.max ? "" : "&sizeMax=" + size.max}`;
    // window.location.href = `/projects/${type}${queryString}`;
    router.push(`/projects/${type}${queryString}`);
  };

  // console.log("locationsData>>>", locationsData);

  // Property type options - memoized to prevent re-creation on every render
  const propertyTypeOptions: SelectOption[] = useMemo(
    () => [
      { value: "Residential", label: "Residential" },
      { value: "Commercial", label: "Commercial" },
      { value: "Condominium", label: "Condominium" },
      { value: "Land", label: "Land" },
    ],
    []
  );

  // Location options - memoized to prevent re-creation on every render
  const locationOptions: SelectOption[] = useMemo(
    () => [
      { value: "All", label: "All" },
      ...locationsData.map((l) => ({
        value: l.attributes.name,
        label: l.attributes.name,
      })),
    ],
    [locationsData]
  );

  const rangeHashMap = useMemo(
    () => ({
      Residential: {
        ranges: [
          { value: "0 - 1500", min: 0, max: 1500 },
          { value: "1500 - 2000", min: 1500, max: 2000 },
          { value: "2000 - 3000", min: 2000, max: 3000 },
          { value: "3000 - 4000", min: 3000, max: 4000 },
        ],
        unit: "sqft",
      },
      Commercial: {
        ranges: [
          { value: "0 - 2000", min: 0, max: 2000 },
          { value: "2000 - 4000", min: 2000, max: 4000 },
          { value: "4000 - 6000", min: 4000, max: 6000 },
          { value: "6000 - 8000", min: 6000, max: 8000 },
        ],
        unit: "sqft",
      },
      Condominium: {
        ranges: [
          { value: "0 - 1500", min: 0, max: 1500 },
          { value: "1500 - 2000", min: 1000, max: 2000 },
          { value: "2000 - 3000", min: 2000, max: 3000 },
        ],
        unit: "sqft",
      },
      Land: {
        ranges: [
          { value: "0 - 3", min: 0, max: 3 },
          { value: "3 - 5", min: 3, max: 5 },
          { value: "5 - 10", min: 5, max: 10 },
          { value: "10 - 20", min: 10, max: 20 },
        ],
        unit: "katha",
      },
    }),
    []
  );

  const currentType = searchFormData.type as keyof typeof rangeHashMap;

  // Unit size options - memoized to prevent re-creation on every render
  const unitSizeOptions: SelectOption[] = useMemo(
    () => [
      { value: "All", label: "All" },
      ...rangeHashMap[currentType].ranges.map((range) => ({
        value: range.value,
        label: `${range.value} ${rangeHashMap[currentType].unit}`,
      })),
    ],
    [currentType, rangeHashMap]
  );

  // Find selected options - memoized to prevent re-calculation on every render
  const selectedPropertyType = useMemo(
    () =>
      propertyTypeOptions.find(
        (option) => option.value === searchFormData.type
      ) || null,
    [propertyTypeOptions, searchFormData.type]
  );

  const selectedLocation = useMemo(
    () =>
      locationOptions.find(
        (option) => option.value === searchFormData.location
      ) || null,
    [locationOptions, searchFormData.location]
  );

  const selectedUnitSize = useMemo(() => {
    const currentSizeValue =
      searchFormData.size.min === null && searchFormData.size.max === null
        ? "All"
        : `${searchFormData.size.min} - ${searchFormData.size.max}`;
    return (
      unitSizeOptions.find((option) => option.value === currentSizeValue) ||
      null
    );
  }, [unitSizeOptions, searchFormData.size.min, searchFormData.size.max]);

  return (
    <div className="absolute right-1/2 transform translate-x-1/2 bottom-2 lg:bottom-8 w-[95%] lg:w-auto z-50 bg-white/90 backdrop-blur-[20px] rounded-sm shadow-lg">
      <form
        className="flex flex-col lg:flex-row items-center justify-center gap-3 lg:gap-12 p-3 sm:p-4 lg:p-6"
        onSubmit={handleSearch}
      >
        {/* Mobile: Grid layout for filters */}
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 lg:gap-0 w-full lg:w-auto">
          {/* Property Type */}
          <div className="flex flex-col gap-2 p-2 sm:p-3 lg:p-4 transition-all duration-300 ease-in-out hover:shadow-lg hover:shadow-gray-300/20">
            <label className="font-['Creato_Display'] font-light text-xs lg:text-sm xl:text-base tracking-wider text-gray-700">
              Property Type
            </label>
            <Select
              value={selectedPropertyType}
              onChange={(selectedOption: SingleValue<SelectOption>) =>
                selectedOption && handleChange("type", selectedOption.value)
              }
              options={propertyTypeOptions}
              styles={customStyles}
              isSearchable={false}
              className="react-select-container"
              classNamePrefix="react-select"
            />
          </div>

          {/* Divider for desktop */}
          <div className="hidden lg:block w-px h-12 bg-gray-300"></div>

          {/* Location */}
          <div className="flex flex-col gap-2 p-2 sm:p-3 lg:p-4 transition-all duration-300 ease-in-out hover:shadow-lg hover:shadow-gray-300/20">
            <label className="font-['Creato_Display'] font-light text-xs lg:text-sm xl:text-base tracking-wider text-gray-700">
              Location
            </label>
            <Select
              value={selectedLocation}
              onChange={(selectedOption: SingleValue<SelectOption>) =>
                selectedOption && handleChange("location", selectedOption.value)
              }
              options={locationOptions}
              styles={customStyles}
              isSearchable={false}
              className="react-select-container"
              classNamePrefix="react-select"
            />
          </div>

          {/* Divider for desktop */}
          <div className="hidden lg:block w-px h-12 bg-gray-300"></div>

          {/* Unit Size */}
          <div className="flex flex-col gap-2 p-2 sm:p-3 lg:p-4 transition-all duration-300 ease-in-out hover:shadow-lg hover:shadow-gray-300/20">
            <label className="font-['Creato_Display'] font-light text-xs lg:text-sm xl:text-base tracking-wider text-gray-700">
              Unit Size
            </label>
            <Select
              value={selectedUnitSize}
              onChange={(selectedOption: SingleValue<SelectOption>) =>
                selectedOption && handleChange("size", selectedOption.value)
              }
              options={unitSizeOptions}
              styles={customStyles}
              isSearchable={false}
              className="react-select-container"
              classNamePrefix="react-select"
            />
          </div>

          {/* Divider for desktop */}
          <div className="hidden lg:block w-px h-12 bg-gray-300"></div>
        </div>

        {/* Search Button */}
        <div className="w-full lg:w-auto p-2 sm:p-3 lg:p-4">
          <BlackBtn name="Search" />
        </div>
      </form>
    </div>
  );
};

export default AdvanceFilterBar;
