import { useEffect, useState } from "react";
import { Filters } from "./SearchFilters";
import clsx from "clsx";
import { useSearchParams } from "react-router";

function UnitTypesSelect({
  filters,
  onSelect,
}: {
  filters: Filters;
  onSelect: (unitTypes: string[]) => void;
}) {
  const [selectedUnitTypes, setSelectedUnitTypes] = useState<string[]>([]);

  const [searchParams, setSearchParams] = useSearchParams();

  useEffect(() => onSelect(selectedUnitTypes), [onSelect, selectedUnitTypes]);

  useEffect(() => {
    const unitTypesValue = searchParams.getAll("unitTypes");

    if (unitTypesValue) setSelectedUnitTypes(unitTypesValue);
  }, [searchParams]);

  return (
    <div className="flex 2xl:gap-[0.556vw] gap-2">
      {filters.unitTypes.map((unitType) => (
        <div
          key={unitType}
          onClick={() => {
            setSelectedUnitTypes((prev) =>
              prev.includes(unitType)
                ? prev.filter((type) => type !== unitType)
                : [...prev, unitType]
            );
            setSearchParams((prev) => {
              if (prev.getAll("unitTypes").includes(unitType))
                prev.delete("unitTypes", unitType);
              else prev.append("unitTypes", unitType);
              return prev;
            });
          }}
          className={clsx(
            "2xl:px-[1.389vw] 2xl:py-[0.833vw] px-5 py-3 2xl:rounded-[2.778vw] rounded-[40px] 2xl:ring-[0.069vw] ring transition-[box-shadow] cursor-pointer",
            selectedUnitTypes.includes(unitType)
              ? "ring-[#00BED7]"
              : "ring-[#E2E2DC]"
          )}
        >
          {unitType}
        </div>
      ))}
    </div>
  );
}

export default UnitTypesSelect;
