import { useState } from 'react';

type Filters = {
  floorPlan: string;
  sqftMin: string;
  sqftMax: string;
  beds: string[];
  baths: string[];
  garage: string[];
  garage_type: string[];
  rooms: string[];
  features: string[];
  architectureStyles: string[];
};

const SearchLogic = () => {
  const initialState: Filters = {
    floorPlan: '',
    sqftMin: '',
    sqftMax: '',
    beds: [],
    baths: [],
    garage: [],
    garage_type: [],
    rooms: [],
    features: [],
    architectureStyles: [],
  };

  const [filters, setFilters] = useState<Filters>(initialState);

  const handleInputChange = (filterType: keyof Filters) => (e: React.ChangeEvent<HTMLInputElement>) => {
    const { value } = e.target;
    setFilters((prevFilters) => ({
      ...prevFilters,
      [filterType]: value,
    }));
  };

  const handleCheckboxChange = (filterType: keyof Filters) => (e: React.ChangeEvent<HTMLInputElement>) => {
    const { value, checked } = e.target;

    setFilters((prevFilters) => ({
      ...prevFilters,
      [filterType]: Array.isArray(prevFilters[filterType])
        ? checked
          ? [...prevFilters[filterType], value] 
          : prevFilters[filterType].filter((item) => item !== value) 
        : prevFilters[filterType], 
    }));
  };
  
  const handleClearFilters = () => {
    setFilters(initialState);
  };

  return {
    filters,
    handleInputChange,
    handleCheckboxChange,
    handleClearFilters,
  };
};

export default SearchLogic;
