import { Suspense } from "react";
import { ProductQueryParams } from "@/types/product";
import { onGetProductPaging } from "@/services/apis/product";
import ProductListClient from "./ProductClient";
import { ResponseStatus, SortDirection, SortField } from "@/types/common";
import LoadingSpinner from "@/components/ui/loading-spinner";
import { onSignInCustomer } from "@/services/apis/customer";
import { onGetAppSettingCustomer } from "@/services/apis/appSetting";
import { SettingAppCustomer } from "@/types/appSetting";

export default async function ManageProductsPage({
  params,
}: {
  params: { customerId: string };
}) {
  const customerId = params.customerId;
  let customerError: string | undefined = "";
  let token = "";
  let settingAppCustomer: SettingAppCustomer = {
    deliveryOptions: { online: false, offline: false },
    beUsername: "",
    beAuthKey: "",
    beUserId: "",
    customerEmail: ""
  };

  try {
    const isSignInCustomer = await onSignInCustomer({ loginId: customerId });
    console.log("isSignInCustomer", isSignInCustomer);
    if (
      !isSignInCustomer ||
      (isSignInCustomer?.status &&
        isSignInCustomer?.status !== ResponseStatus.SUCCESS)
    ) {
      customerError = "Customer authentication failed";
    }

    token = isSignInCustomer?.data?.accessToken;

    const isSettingAppCustomer = await onGetAppSettingCustomer(
      { customerId: customerId },
      token
    );
    console.log("isSettingAppCustomer", isSettingAppCustomer);
    settingAppCustomer = isSettingAppCustomer.data as SettingAppCustomer;

    if (
      !isSettingAppCustomer ||
      isSettingAppCustomer?.status !== ResponseStatus.SUCCESS
    ) {
      customerError = "Customer app settings not found";
    }
  } catch (error) {
    console.log("error", error);
    customerError = "Customer not found";
  }

  if (customerError !== "") {
    return (
      <div className="min-h-screen bg-gray-50 py-12 px-4 flex items-center justify-center">
        <div className="bg-white rounded-xl shadow-sm p-8 max-w-2xl w-full">
          <div className={`text-4xl mb-4 text-red-500 `}>{customerError}</div>
        </div>
      </div>
    );
  }

  const queryParams: ProductQueryParams = {
    customerId: customerId,
    pageNumber: 1,
    pageSize: 10,
    searchKeyName: "",
    sortField: SortField.createdTime,
    sortDirection: SortDirection.DESC,
  };
  console.log("queryParams", queryParams);
  try {
    const response = await onGetProductPaging(queryParams, token);
    console.log("response", response?.data?.content);

    if (!response) {
      throw new Error("Couldn't get product");
    }

    return (
      <Suspense fallback={<LoadingSpinner />}>
        <ProductListClient
          initialData={response?.data}
          initialQuery={queryParams}
          customerId={customerId}
          customerToken={token}
          isSettingAppCustomer={settingAppCustomer}
        />
      </Suspense>
    );
  } catch (error) {
    return (
      <div className="min-h-screen bg-gray-50 py-12 px-4 flex items-center justify-center">
        <div className="bg-white rounded-xl shadow-sm p-8 max-w-md w-full">
          <div className={`text-4xl mb-4 text-red-500 `}>
            Error fetching products
          </div>
        </div>
      </div>
    );
  }
}
