import { useState } from "react";
import { useRouter } from "next/navigation";
import SelectAtom from "@/components/atoms/SelectAtom";
import Link from "next/link";
import LocationsDataFetcher from "@/utils/locationDatafetcher";

interface MobileFilterProps {
  extraClassName?: string;
  isVertical?: boolean;
}

// Property type options
const propertyTypeOptions = [
  { value: "Residential", label: "Residential" },
  { value: "Commercial", label: "Commercial" },
  { value: "Condominium", label: "Condominium" },
  { value: "Land", label: "Land" },
];

// Property status options
const propertyStatusOptions = [
  { value: "All", label: "All" },
  { value: "Upcoming", label: "Upcoming" },
  { value: "Ongoing", label: "Ongoing" },
  { value: "Completed", label: "Completed" },
];

// Unit size options based on property type
const rangeHashMap = {
  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 SearchFilter = ({ isVertical, extraClassName }: MobileFilterProps) => {
  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,
    },
    status: "All",
  });

  const router = useRouter();

  const currentType = searchFormData.type as keyof typeof rangeHashMap;

  const unitSizeOptions = [
    { value: "All", label: "All" },
    ...rangeHashMap[currentType].ranges.map((range) => ({
      value: range.value,
      label: `${range.value} ${rangeHashMap[currentType].unit}`,
    })),
  ];

  // Location options
  const locationOptions = [
    { value: "All", label: "All" },
    ...locationsData.map((l) => ({
      value: l.attributes.name,
      label: l.attributes.name,
    })),
  ];

  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, status } = searchFormData;

    const queryString = `?location=${location}${
      !size.min ? "" : "&sizeMin=" + size.min
    }${!size.max ? "" : "&sizeMax=" + size.max}${
      status !== "All" ? "&status=" + status : ""
    }`;

    router.push(`/projects/${type}${queryString}`);
  };
  return (
    <div className={`w-full  mx-auto filter ${extraClassName}`}>
      {/* Mobile Container */}
      <div className={`${isVertical ? "p-0" : "p-6"}`}>
        <form
          onSubmit={handleSearch}
          className={`${
            isVertical ? "space-y-8" : "lg:space-y-0 lg:flex lg:justify-center"
          }`}
        >
          {/* Property Type */}
          <div className="transition-all duration-500 ease-out transform opacity-100 translate-y-0 scale-100">
            <SelectAtom
              label="Property Type"
              name="type"
              value={searchFormData.type}
              onChange={handleChange}
              options={propertyTypeOptions}
              placeholder="Select Property Type"
            />
          </div>

          {/* Location */}
          <div className="transition-all duration-500 ease-out transform opacity-100 translate-y-0 scale-100">
            <SelectAtom
              label="Location"
              name="location"
              value={searchFormData.location}
              onChange={handleChange}
              options={locationOptions}
              placeholder="Select Location"
            />
          </div>

          {/* Unit Size */}
          <div className="transition-all duration-500 ease-out transform opacity-100 translate-y-0 scale-100">
            <SelectAtom
              label="Unit Size"
              name="size"
              value={
                searchFormData.size.min === null &&
                searchFormData.size.max === null
                  ? "All"
                  : `${searchFormData.size.min} - ${searchFormData.size.max}`
              }
              onChange={handleChange}
              options={unitSizeOptions}
              placeholder="Select Unit Size"
            />
          </div>

          {/* Property Status */}
          <div className="transition-all duration-500 ease-out transform opacity-100 translate-y-0 scale-100">
            <SelectAtom
              label="Property Status"
              name="status"
              value={searchFormData.status}
              onChange={handleChange}
              options={propertyStatusOptions}
              placeholder="Select Property Status"
            />
          </div>

          {/* Search Button */}
          <div className="transition-all duration-500 ease-out transform opacity-100 translate-y-0 scale-100 flex items-center lg:min-w-[312px] min-h-20 bg-[#E8E8E8] justify-center">
            <Link
              href={"/properties"}
              className="max-w-44 max-h-16 bg-[#DD577F] hover:bg-[#333333] text-white font-creato font-medium text-base py-3 px-10 transition-colors duration-200 cursor-pointer"
            >
              Search
            </Link>

            {/* <SearchButton type="submit">Search</SearchButton> */}
          </div>
        </form>
      </div>
    </div>
  );
};

export default SearchFilter;
