summaryrefslogtreecommitdiff
path: root/src/components/elements/Filter.js
blob: f2051ba8f648c230a41afa5888ecabd73e105be5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import BottomPopup from "./BottomPopup";

const Filter = ({ 
  isActive,
  closeFilter,
  defaultRoute,
  defaultPriceFrom,
  defaultPriceTo,
  defaultCategory,
  defaultBrand,
  defaultOrderBy,
  searchResults,
  disableFilter = []
}) => {
  const router = useRouter();

  const [priceFrom, setPriceFrom] = useState(defaultPriceFrom);
  const [priceTo, setPriceTo] = useState(defaultPriceTo);
  const [orderBy, setOrderBy] = useState(defaultOrderBy);
  const [selectedCategory, setSelectedCategory] = useState(defaultCategory);
  const [selectedBrand, setSelectedBrand] = useState(defaultBrand);
  const [categories, setCategories] = useState([]);
  const [brands, setBrands] = useState([]);

  const filterRoute = () => {
    let filterRoute = [];
    let filterRoutePrefix = '?';
    if (selectedBrand) filterRoute.push(`brand=${selectedBrand}`);
    if (selectedCategory) filterRoute.push(`category=${selectedCategory}`);
    if (priceFrom) filterRoute.push(`price_from=${priceFrom}`);
    if (priceTo) filterRoute.push(`price_to=${priceTo}`);
    if (orderBy) filterRoute.push(`order_by=${orderBy}`);

    if (defaultRoute.includes('?')) filterRoutePrefix = '&';
    if (filterRoute.length > 0) {
      filterRoute = filterRoutePrefix + filterRoute.join('&');
    } else {
      filterRoute = '';
    }

    return defaultRoute + filterRoute;
  }

  useEffect(() => {
    const filterCategory = searchResults.facet_counts.facet_fields.category_name_str.filter((category, index) => {
      if (index % 2 == 0) {
        const productCountInCategory = searchResults.facet_counts.facet_fields.category_name_str[index + 1];
        if (productCountInCategory > 0) return category;
      }
    });
    setCategories(filterCategory);

    const filterBrand = searchResults.facet_counts.facet_fields.brand_str.filter((brand, index) => {
      if (index % 2 == 0) {
        const productCountInBrand = searchResults.facet_counts.facet_fields.brand_str[index + 1];
        if (productCountInBrand > 0) return brand;
      }
    });
    setBrands(filterBrand);
  }, [searchResults]);

  const submit = (e) => {
    e.preventDefault();
    closeFilter();
    router.push(filterRoute(), undefined, { scroll: false });
  }

  const reset = () => {
    setSelectedBrand('');
    setSelectedCategory('');
    setPriceFrom('');
    setPriceTo('');
    setOrderBy('');
  }

  const changeOrderBy = (value) => {
    if (orderBy == value) {
      setOrderBy('');
    } else {
      setOrderBy(value);
    }
  }

  const sortOptions = [
    {
      name: 'Harga Terendah',
      value: 'price-asc',
    }, 
    {
      name: 'Harga Tertinggi',
      value: 'price-desc',
    },
    {
      name: 'Populer',
      value: 'popular',
    },
    {
      name: 'Ready Stock',
      value: 'stock',
    },
  ];

  return (
    <>
      <BottomPopup active={isActive} closePopup={closeFilter} title="Filter Produk">
        <form className="flex flex-col gap-y-4" onSubmit={submit}>
          {(selectedBrand || selectedCategory || priceFrom || priceTo || orderBy) && (
            <button type="button" className="text-yellow_r-11 font-semibold ml-auto" onClick={reset}>
              Reset Filter
            </button>
          )}

          {!disableFilter.includes('orderBy') && (
            <div>
              <label>Urutkan</label>
              <div className="flex gap-2 mt-2 overflow-x-auto w-full">
              {sortOptions.map((sortOption, index) => (
                <button 
                  key={index}
                  type="button" 
                  className={"p-2 rounded border border-gray_r-6 flex-shrink-0" + (orderBy == sortOption.value ? ' border-yellow_r-10 bg-yellow_r-3 text-yellow_r-11' : '')} 
                  onClick={() => changeOrderBy(sortOption.value)}
                >
                  {sortOption.name}
                </button>
              ))}
              </div>
            </div>
          )}

          {!disableFilter.includes('category') && (
            <div>
              <label>Kategori</label>
              <select className="form-input mt-2" value={selectedCategory} onChange={(e) => setSelectedCategory(e.target.value)}>
                <option value="">Pilih kategori...</option>
                {categories?.map((category, index) => (
                  <option key={index} value={category}>{category}</option>
                ))}
              </select>
            </div>
          )}

          {!disableFilter.includes('brand') && (
            <div>
              <label>Brand</label>
              <select className="form-input mt-2" value={selectedBrand} onChange={(e) => setSelectedBrand(e.target.value)}>
                <option value="">Pilih brand...</option>
                {brands?.map((brand, index) => (
                  <option key={index} value={brand}>{brand}</option>
                ))}
              </select>
            </div>
          )}

          {!disableFilter.includes('price') && (
            <div>
              <label>Harga</label>
              <div className="flex gap-x-4 mt-2 items-center">
                <input className="form-input" type="number" placeholder="Dari" value={priceFrom} onChange={(e) => setPriceFrom(e.target.value)}/>
                <span>&mdash;</span>
                <input className="form-input" type="number" placeholder="Sampai" value={priceTo} onChange={(e) => setPriceTo(e.target.value)}/>
              </div>
            </div>
          )}
          <button type="submit" className="btn-yellow font-semibold mt-2 w-full">
            Terapkan Filter
          </button>
        </form>
      </BottomPopup>
    </>
  )
};

export default Filter;