import ErrorMessages from "@/components/common/error-messages";
import PaymentTypeForm from "@/components/payment-type/payment-type-form";
import PaymentTypeList from "@/components/payment-type/payment-type-list";
import getData from "@/utils/fetch";
import { Metadata } from "next";
import PaymentTypeContent from "./content";
export const metadata: Metadata = {
  title: "payment type",
};

export default async function PaymentType(context: any) {
  const { searchParams } = context;
  const paymentId = searchParams?.id;
  let singlePayment = undefined;
  if (paymentId) {
    singlePayment = await editForm(paymentId);
  }

  const payment_type_response = await getData("/api/v1/payment-types");
  if (!payment_type_response?.success) {
    return <ErrorMessages message={payment_type_response?.message} />;
  }
  const {
    data: { data: paymentType },
    data: { pagination },
  } = payment_type_response;
  return (
    <div>
      <PaymentTypeContent />
      <div className="overflow-hidden shadow">
        <PaymentTypeList
          initPaymentType={paymentType}
          initPagination={pagination}
        />
        {singlePayment && (
          <PaymentTypeForm paymentType={singlePayment} mode="edit" />
        )}
      </div>
    </div>
  );
}

const editForm = async (id: string) => {
  const { data: payment } = await getData(`/api/v1/payment-types/${id}`);
  return payment;
};
