import { Button, CircularProgress, Grid } from "@mui/material";
import SearchResults, { Column } from "../SearchResults/SearchResults";
import { PickOrderResult } from "@/app/api/pickOrder";
import { useTranslation } from "react-i18next";
import { useCallback, useEffect, useMemo, useState } from "react";
import { isEmpty, upperCase, upperFirst } from "lodash";
import { arrayToDateString } from "@/app/utils/formatUtil";
import {
  consolidatePickOrder,
  fetchPickOrderClient,
} from "@/app/api/pickOrder/actions";
import useUploadContext from "../UploadProvider/useUploadContext";

interface Props {
  filteredPickOrders: PickOrderResult[];
  filterArgs: Record<string, any>;
}

const PickOrders: React.FC<Props> = ({ filteredPickOrders, filterArgs }) => {
  const { t } = useTranslation("pickOrder");
  const [selectedRows, setSelectedRows] = useState<(string | number)[]>([]);
  const [filteredPickOrder, setFilteredPickOrder] = useState(
    [] as PickOrderResult[],
  );
  const { setIsUploading } = useUploadContext();
  const [isLoading, setIsLoading] = useState(false);
  const [pagingController, setPagingController] = useState({
    pageNum: 0,
    pageSize: 10,
  });
  const [totalCount, setTotalCount] = useState<number>();

  const handleConsolidatedRows = useCallback(async () => {
    console.log(selectedRows);
    setIsUploading(true);
    try {
      const res = await consolidatePickOrder(selectedRows as number[]);
      if (res) {
        console.log(res);
      }
    } catch {
      setIsUploading(false);
    }
    fetchNewPagePickOrder(pagingController, filterArgs);
    setIsUploading(false);
  }, [selectedRows, pagingController]);

  const fetchNewPagePickOrder = useCallback(
    async (
      pagingController: Record<string, number>,
      filterArgs: Record<string, number>,
    ) => {
      setIsLoading(true);
      const params = {
        ...pagingController,
        ...filterArgs,
      };
      const res = await fetchPickOrderClient(params);
      if (res) {
        console.log(res);
        setFilteredPickOrder(res.records);
        setTotalCount(res.total);
      }
      setIsLoading(false);
    },
    [],
  );

  useEffect(() => {
    fetchNewPagePickOrder(pagingController, filterArgs);
  }, [fetchNewPagePickOrder, pagingController, filterArgs]);

  const columns = useMemo<Column<PickOrderResult>[]>(
    () => [
      {
        name: "id",
        label: "",
        type: "checkbox",
        disabled: (params) => {
          return !isEmpty(params.consoCode);
        },
      },
      {
        name: "code",
        label: t("Code"),
      },
      {
        name: "consoCode",
        label: t("Consolidated Code"),
        renderCell: (params) => {
          return params.consoCode ?? "";
        },
      },
      {
        name: "type",
        label: t("type"),
        renderCell: (params) => {
          return upperCase(params.type);
        },
      },
      {
        name: "items",
        label: t("Items"),
        renderCell: (params) => {
          return params.items?.map((i) => i.name).join(", ");
        },
      },
      {
        name: "targetDate",
        label: t("Target Date"),
        renderCell: (params) => {
          return arrayToDateString(params.targetDate);
        },
      },
      {
        name: "releasedBy",
        label: t("Released By"),
      },
      {
        name: "status",
        label: t("Status"),
        renderCell: (params) => {
          return upperFirst(params.status);
        },
      },
    ],
    [t],
  );

  return (
    <Grid container rowGap={1}>
      <Grid item xs={3}>
        <Button
          disabled={selectedRows.length < 1}
          variant="outlined"
          onClick={handleConsolidatedRows}
        >
          {t("Consolidate")}
        </Button>
      </Grid>
      <Grid item xs={12}>
        {isLoading ? (
          <CircularProgress size={40} />
        ) : (
          <SearchResults<PickOrderResult>
            items={filteredPickOrder}
            columns={columns}
            pagingController={pagingController}
            setPagingController={setPagingController}
            totalCount={totalCount}
            checkboxIds={selectedRows!}
            setCheckboxIds={setSelectedRows}
          />
        )}
      </Grid>
    </Grid>
  );
};

export default PickOrders;
