import React, { useEffect, useMemo, useState } from "react";
import DataIteration from "../Helpers/DataIteration";
import AvailableJobsCard from "../Cards/AvailableJobsCard";

export default function MainSection({
  className,
  marketPlaceProduct,
  categories,
}) {
  // Creating All cart..
  let marketCategories = useMemo(
    () => ({ All: "All", ...categories }),
    [categories]
  );
  const [tab, setTab] = useState(marketCategories.All);

  // Convert to array in order to map
  const mappedArray = Object.entries(marketCategories).map(([key, value]) => {
    return { key, value };
  });

  const [products, setProducts] = useState([]);
  const tabHandler = (value) => {
    setTab(value);
  };
  useEffect(() => {
    if (tab === marketCategories.All) {
      setProducts(marketPlaceProduct);
    } else {
      const filteredProducts = marketPlaceProduct.filter((product) =>
        product.category.includes(tab)
      );
      setProducts(filteredProducts);
    }
  }, [tab, marketPlaceProduct, categories, marketCategories]);

  return (
    <div className={`market-place-section w-full ${className || ""}`}>
      <div className="market-place-wrapper w-full">
        <div className="filter-navigate-area lg:flex justify-between mb-8 items-center">
          <div className="tab-item lg:mb-0 mb-5">
            <div className="md:flex md:space-x-8 space-x-2">
              {mappedArray.map(({ key, value }) => (
                <span
                  onClick={() => tabHandler(key)}
                  className={`md:text-[18px] text-md  text-dark-gray dark:text-white hover:text-pink border-b hover:border-pink font-medium cursor-pointer ${
                    tab === key
                      ? "text-pink border-pink"
                      : " border-transparent"
                  }`}
                >
                  {value}
                </span>
              ))}
            </div>
          </div>
        </div>
        <div className="filter-navigate-content w-full min-h-screen">
          <div className="grid lg:grid-cols-3 sm:grid-cols-2 gap-[30px]">
            <DataIteration
              datas={products}
              startLength={process.env.REACT_APP_ZERO_STATE}
              endLength={products?.length}
            >
              {({ datas }) => (
                <AvailableJobsCard key={datas.id} datas={datas} />
              )}
            </DataIteration>
          </div>
        </div>
      </div>
    </div>
  );
}
