"use client";
import { InventoryLotLineResult, InventoryResult } from "@/app/api/inventory";
import { useTranslation } from "react-i18next";
import SearchBox, { Criterion } from "../SearchBox";
import { useCallback, useEffect, useMemo, useState } from "react";
import { orderBy, uniq, uniqBy } from "lodash";
import SearchResults, { Column } from "../SearchResults";
import { CheckCircleOutline, DoDisturb } from "@mui/icons-material";
import InventoryTable from "./InventoryTable";
import { defaultPagingController } from "../SearchResults/SearchResults";
import InventoryLotLineTable from "./InventoryLotLineTable";
import { SearchInventory, SearchInventoryLotLine, fetchInventories, fetchInventoryLotLines } from "@/app/api/inventory/actions";

interface Props {
  inventories: InventoryResult[];
}

type SearchQuery = Partial<
  Omit<
    InventoryResult,
    | "id"
    | "qty"
    | "uomCode"
    | "uomUdfudesc"
    | "germPerSmallestUnit"
    | "qtyPerSmallestUnit"
    | "itemSmallestUnit"
    | "price"
    | "description"
    | "category"
  >
>;
type SearchParamNames = keyof SearchQuery;

const InventorySearch: React.FC<Props> = ({ inventories }) => {
  const { t } = useTranslation(["inventory", "common"]);

  // Inventory
  const [filteredInventories, setFilteredInventories] = useState<InventoryResult[]>([]);
  const [inventoriesPagingController, setInventoriesPagingController] = useState(defaultPagingController)
  const [inventoriesTotalCount, setInventoriesTotalCount] = useState(0)
  const [item, setItem] = useState<InventoryResult | null>(null)

  // Inventory Lot Line
  const [filteredInventoryLotLines, setFilteredInventoryLotLines] = useState<InventoryLotLineResult[]>([]);
  const [inventoryLotLinesPagingController, setInventoryLotLinesPagingController] = useState(defaultPagingController)
  const [inventoryLotLinesTotalCount, setInventoryLotLinesTotalCount] = useState(0)

  const [inputs, setInputs] = useState<Record<SearchParamNames, string>>({
    itemId: "",
    itemCode: "",
    itemName: "",
    itemType: "",
    onHandQty: "",
    onHoldQty: "",
    unavailableQty: "",
    availableQty: "",
    currencyName: "",
    status: "",
    baseUom: "",
  });

  const searchCriteria: Criterion<SearchParamNames>[] = useMemo(
    () => [
      { label: t("Code"), paramName: "itemCode", type: "text" },
      { label: t("Name"), paramName: "itemName", type: "text" },
      {
        label: t("Type"),
        paramName: "itemType",
        type: "select",
        options: uniq(inventories.map((i) => i.itemType)),
      },
      // {
      //   label: t("Status"),
      //   paramName: "status",
      //   type: "select",
      //   options: uniq(inventories.map((i) => i.status)),
      // },
    ],
    [t],
  );

  const refetchInventoryData = useCallback(async (
    query: Record<SearchParamNames, string>,
    actionType: "reset" | "search" | "paging"
  ) => {
    const params: SearchInventory = {
      code: query?.itemCode ?? '',
      name: query?.itemName ?? '',
      type: query?.itemType.toLowerCase() === "all" ? '' : query?.itemType ?? '',
      pageNum: inventoriesPagingController.pageNum - 1,
      pageSize: inventoriesPagingController.pageSize
    }

    const response = await fetchInventories(params)

    if (response) {
      console.log(response)
      setInventoriesTotalCount(response.total);
      switch (actionType) {
        case "reset":
        case "search":
          setFilteredInventories(() => response.records);
          break;
        case "paging":
          setFilteredInventories((fi) =>
            orderBy(
              uniqBy([...fi, ...response.records], "id"),
              ["id"], ["desc"]
            ));
      }
    }
  }, [inventoriesPagingController, setInventoriesPagingController])

  useEffect(() => {
    refetchInventoryData(inputs, "paging")
  }, [inventoriesPagingController])

  const refetchInventoryLotLineData = useCallback(async (
    itemId: number | null,
    actionType: "reset" | "search" | "paging"
  ) => {
    if (!itemId) {
      setItem(null)
      setInventoryLotLinesTotalCount(0);
      setFilteredInventoryLotLines([])
      return
    }

    const params: SearchInventoryLotLine = {
      itemId: itemId,
      pageNum: inventoriesPagingController.pageNum - 1,
      pageSize: inventoriesPagingController.pageSize
    }

    const response = await fetchInventoryLotLines(params)

    if (response) {
      setInventoryLotLinesTotalCount(response.total);
      switch (actionType) {
        case "reset":
        case "search":
          setFilteredInventoryLotLines(() => response.records);
          break;
        case "paging":
          setFilteredInventoryLotLines((fi) =>
            orderBy(
              uniqBy([...fi, ...response.records], "id"),
              ["id"], ["desc"]
            ));
      }
    }
  }, [inventoriesPagingController, setInventoriesPagingController])

  useEffect(() => {
    refetchInventoryData(inputs, "paging")
  }, [inventoriesPagingController])

  const onReset = useCallback(() => {
    refetchInventoryData(inputs, "reset");
    refetchInventoryLotLineData(null, "reset");
    // setFilteredInventories(inventories);
  }, []);

  const onInventoryRowClick = useCallback((item: InventoryResult) => {
    setItem(item)
    refetchInventoryLotLineData(item.itemId, "search")
  }, [])

  return (
    <>
      <SearchBox
        criteria={searchCriteria}
        onSearch={(query) => {
          // console.log(query)
          // console.log(inventories)
          setInputs(() => query)
          refetchInventoryData(query, "search")
          // setFilteredInventories(
          //   inventories.filter(
          //     (i) =>
          //       i.itemCode.toLowerCase().includes(query.itemCode.toLowerCase()) &&
          //       i.itemName.toLowerCase().includes(query.itemName.toLowerCase()) &&
          //       (query.itemType == "All" ||
          //         i.itemType.toLowerCase().includes(query.itemType.toLowerCase())) &&
          //       (query.status == "All" ||
          //         i.status.toLowerCase().includes(query.status.toLowerCase())),
          //   ),
          // );
        }}
        onReset={onReset}
      />
      <InventoryTable
        inventories={filteredInventories}
        pagingController={inventoriesPagingController}
        setPagingController={setInventoriesPagingController}
        totalCount={inventoriesTotalCount}
        onRowClick={onInventoryRowClick}
      />
      <InventoryLotLineTable
        inventoryLotLines={filteredInventoryLotLines}
        pagingController={inventoryLotLinesPagingController}
        setPagingController={setInventoryLotLinesPagingController}
        totalCount={inventoryLotLinesTotalCount}
        item={item}
      />
    </>
  );
};

export default InventorySearch;
