"use client";
import { PickOrderResult } from "@/app/api/pickorder";
import { SearchParams } from "@/app/utils/fetchUtil";
import { useCallback, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import SearchBox, { Criterion } from "../SearchBox";
import SearchResults, { Column } from "../SearchResults";
import {
  flatten,
  groupBy,
  intersectionWith,
  isEmpty,
  map,
  sortBy,
  sortedUniq,
  uniqBy,
  upperCase,
  upperFirst,
} from "lodash";
import {
  arrayToDateString,
  arrayToDayjs,
  dateStringToDayjs,
} from "@/app/utils/formatUtil";
import dayjs from "dayjs";
import { Button, Grid, Stack, Tab, Tabs, TabsProps } from "@mui/material";
import PickOrders from "./PickOrders";
import ConsolidatedPickOrders from "./ConsolidatedPickOrders";

import { getServerI18n } from "@/i18n";
interface Props {
  pickOrders: PickOrderResult[];
}

type SearchQuery = Partial<
  Omit<PickOrderResult, "id" | "consoCode" | "completeDate">
>;

type SearchParamNames = keyof SearchQuery;

const PickOrderSearch: React.FC<Props> = ({
    pickOrders,
}) => {
    const { t } = useTranslation("pickOrder");

  const [filteredPickOrders, setFilteredPickOrders] = useState(pickOrders);
  const [filterArgs, setFilterArgs] = useState<Record<string, any>>({});
  const [tabIndex, setTabIndex] = useState(0);
  const handleTabChange = useCallback<NonNullable<TabsProps["onChange"]>>(
    (_e, newValue) => {
      setTabIndex(newValue);
    },
    []
  );

  const searchCriteria: Criterion<SearchParamNames>[] = useMemo(
    () => [
      { label: t("Code"), paramName: "code", type: "text" },
      {
        label: t("Target Date From"),
        label2: t("Target Date To"),
        paramName: "targetDate",
        type: "dateRange",
      },
      {
        label: t("Type"),
        paramName: "type",
        type: "autocomplete",
        options: sortBy(
          uniqBy(
            pickOrders.map((po) => ({
              value: po.type,
              label: t(upperCase(po.type)),
            })),
            "value"
          ),
          "label"
        ),
      },
      {
        label: t("Status"),
        paramName: "status",
        type: "autocomplete",
        options: sortBy(
          uniqBy(
            pickOrders.map((po) => ({
              value: po.status,
              label: t(upperFirst(po.status)),
            })),
            "value"
          ),
          "label"
        ),
      },
      {
        label: t("Items"),
        paramName: "items",
        type: "autocomplete", // multiple: true,
        options: uniqBy(
          flatten(
            sortBy(
              pickOrders.map((po) =>
                po.items
                  ? po.items.map((item) => ({
                      value: item.name,
                      label: item.name,
                      // group: item.type
                    }))
                  : []
              ),
              "label"
            )
          ),
          "value"
        ),
      },
    ],
    [t]
  );

  const onReset = useCallback(() => {
    setFilteredPickOrders(pickOrders);
  }, [pickOrders]);

  return (
    <>
      <SearchBox
        criteria={searchCriteria}
        onSearch={(query) => {
          setFilterArgs({ ...query }); // modify later
          setFilteredPickOrders(
            pickOrders.filter((po) => {
              const poTargetDateStr = arrayToDayjs(po.targetDate);

              // console.log(intersectionWith(po.items?.map(item => item.name), query.items))
              return (
                po.code.toLowerCase().includes(query.code.toLowerCase()) &&
                (isEmpty(query.targetDate) ||
                  poTargetDateStr.isSame(query.targetDate) ||
                  poTargetDateStr.isAfter(query.targetDate)) &&
                (isEmpty(query.targetDateTo) ||
                  poTargetDateStr.isSame(query.targetDateTo) ||
                  poTargetDateStr.isBefore(query.targetDateTo)) &&
                (intersectionWith(["All"], query.items).length > 0 ||
                  intersectionWith(
                    po.items?.map((item) => item.name),
                    query.items
                  ).length > 0) &&
                (query.status.toLowerCase() == "all" ||
                  po.status
                    .toLowerCase()
                    .includes(query.status.toLowerCase())) &&
                (query.type.toLowerCase() == "all" ||
                  po.type.toLowerCase().includes(query.type.toLowerCase()))
              );
            })
          );
        }}
        onReset={onReset}
      />
      <Tabs value={tabIndex} onChange={handleTabChange} variant="scrollable">
        <Tab label={t("Pick Orders")} iconPosition="end" />
        <Tab label={t("Consolidated Pick Orders")} iconPosition="end" />
      </Tabs>
      {tabIndex === 0 && (
        <PickOrders
          filteredPickOrders={filteredPickOrders}
          filterArgs={filterArgs}
        />
      )}
      {tabIndex === 1 && <ConsolidatedPickOrders filterArgs={filterArgs} />}
    </>
  );
};

export default PickOrderSearch;
