import ErrorMessages from "@/components/common/error-messages";
import ProductCategoryForm from "@/components/product-categories/product-category-form";
import ProductCategoryList from "@/components/product-categories/product-category-list";
import getData from "@/utils/fetch";
import { Metadata } from "next";
import ProductCategoryContent from "./content";
export const metadata: Metadata = {
  title: "product category",
};

export default async function ProductCategory(context: any) {
  const { searchParams } = context;
  const categoryId = searchParams?.id;
  let singleCategory = undefined;
  if (categoryId) {
    singleCategory = await editForm(categoryId);
  }
  const categoryResponse = await getData("/api/v1/product-categories");
  if (!categoryResponse?.success) {
    return <ErrorMessages message={categoryResponse?.message} />;
  }
  const {
    data: { data: productCategory },
    data: { pagination },
  } = categoryResponse;
  return (
    <div>
      <ProductCategoryContent />
      <div className="overflow-hidden shadow">
        <ProductCategoryList
          initProductCategory={productCategory}
          initPagination={pagination}
        />
        {singleCategory && (
          <ProductCategoryForm productCategory={singleCategory} mode="edit" />
        )}
      </div>
    </div>
  );
}

const editForm = async (id: string) => {
  const { data: category } = await getData(`/api/v1/product-categories/${id}`);
  return category;
};
