"use client";

import { InventoryResult } from "@/app/api/inventory";
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { Column } from "../SearchResults";
import SearchResults, {
  defaultPagingController,
  defaultSetPagingController,
} from "../SearchResults/SearchResults";

interface Props {
  inventories: InventoryResult[];
  setPagingController: defaultSetPagingController;
  pagingController: typeof defaultPagingController;
  totalCount: number;
  onRowClick: (item: InventoryResult) => void;
}

const StockIssueInventoryTable: React.FC<Props> = ({
  inventories,
  pagingController,
  setPagingController,
  totalCount,
  onRowClick,
}) => {
  const { t } = useTranslation(["stockIssue", "common"]);

  const columns = useMemo<Column<InventoryResult>[]>(
    () => [
      { name: "itemCode", label: t("Code") },
      { name: "itemName", label: t("Name") },
      {
        name: "itemType",
        label: t("Type"),
        renderCell: (params) => {
          const code = params.itemType?.trim() ?? "";
          if (!code) return "—";
          const fromCommon = t(code, { ns: "common", defaultValue: code });
          return fromCommon !== code ? fromCommon : t(code, { defaultValue: code });
        },
      },
      {
        name: "availableQty",
        label: t("Available Qty"),
        align: "right",
        headerAlign: "right",
        type: "integer",
      },
      {
        name: "uomUdfudesc",
        label: t("Stock UoM"),
        align: "left",
        headerAlign: "left",
      },
    ],
    [t],
  );

  return (
    <SearchResults<InventoryResult>
      items={inventories}
      columns={columns}
      pagingController={pagingController}
      setPagingController={setPagingController}
      totalCount={totalCount}
      onRowClick={onRowClick}
    />
  );
};

export default StockIssueInventoryTable;
