import {
  Box,
  Button,
  CircularProgress,
  Grid,
  Modal,
  ModalProps,
  Typography,
} from "@mui/material";
import { GridToolbarContainer } from "@mui/x-data-grid";
import {
  FooterPropsOverrides,
  GridColDef,
  GridRowSelectionModel,
  useGridApiRef,
} from "@mui/x-data-grid";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import StyledDataGrid from "../StyledDataGrid";
import SearchResults, {
  Column,
  defaultPagingController,
} from "../SearchResults/SearchResults";
import { ByItemsSummary, ConsoPickOrderResult, PickOrderLine, PickOrderResult } from "@/app/api/pickorder";
import { useRouter, useSearchParams } from "next/navigation";
import ConsolidatePickOrderItemSum from "./ConsolidatePickOrderItemSum";
import ConsolidatePickOrderSum from "./ConsolidatePickOrderSum";
import { GridInputRowSelectionModel } from "@mui/x-data-grid";
import {
  fetchConsoDetail,
  fetchConsoPickOrderClient,
} from "@/app/api/pickorder/actions";
import { EditNote } from "@mui/icons-material";

interface Props {
  filterArgs: Record<string, any>;
}

const style = {
  position: "absolute",
  top: "50%",
  left: "50%",
  transform: "translate(-50%, -50%)",
  bgcolor: "background.paper",
  pt: 5,
  px: 5,
  pb: 10,
  width: 1500,
};

const ConsolidatedPickOrders: React.FC<Props> = ({ filterArgs }) => {
  const { t } = useTranslation("pickOrder");
  const router = useRouter();
  const apiRef = useGridApiRef();
  const [filteredPickOrders, setFilteredPickOrders] = useState(
    [] as ConsoPickOrderResult[]
  );
  const [isLoading, setIsLoading] = useState(false);
  const [modalOpen, setModalOpen] = useState(false); //change back to false
  const [consoCode, setConsoCode] = useState<string | undefined>(); ///change back to undefined
  const [revertIds, setRevertIds] = useState<GridInputRowSelectionModel>([]);
  const [totalCount, setTotalCount] = useState<number>();

  const [byPickOrderRows, setByPickOrderRows] = useState<Omit<PickOrderResult, "items">[] | undefined>(undefined);
  const [byItemsRows, setByItemsRows] = useState<ByItemsSummary[] | undefined>(undefined);

  const openDetailModal = useCallback((consoCode: string) => {
    setConsoCode(consoCode);
    setModalOpen(true);
  }, []);

  const closeDetailModal = useCallback(() => {
    setModalOpen(false);
    setConsoCode(undefined);
  }, []);

  const onDetailClick = useCallback(
    (pickOrder: any) => {
      console.log(pickOrder);
      openDetailModal(pickOrder.consoCode);
    },
    [openDetailModal]
  );
  const columns = useMemo<Column<ConsoPickOrderResult>[]>(
    () => [
      {
        name: "id",
        label: t("Detail"),
        onClick: onDetailClick,
        buttonIcon: <EditNote />,
      },
      {
        name: "consoCode",
        label: t("consoCode"),
      },
    ],
    []
  );
  const [pagingController, setPagingController] = useState(
    defaultPagingController
  );

  // pass conso code back to assign
  // pass user back to assign
  const fetchNewPageConsoPickOrder = useCallback(
    async (
      pagingController: Record<string, number>,
      filterArgs: Record<string, number>
    ) => {
      setIsLoading(true);
      const params = {
        ...pagingController,
        ...filterArgs,
      };
      const res = await fetchConsoPickOrderClient(params);
      if (res) {
        console.log(res);
        setFilteredPickOrders(res.records);
        setTotalCount(res.total);
      }
      setIsLoading(false);
    },
    []
  );

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

  const closeHandler = useCallback<NonNullable<ModalProps["onClose"]>>(
    (...args) => {
      closeDetailModal();
      //   reset();
    },
    [closeDetailModal]
  );

  const handleRelease = useCallback(() => {
    console.log("release");
    router.push(`/pickorder/detail?consoCode=${consoCode}`);
  }, [router, consoCode]);

  const handleConsolidate_revert = useCallback(() => {
    console.log(revertIds);
  }, [revertIds]);

  const fetchConso = useCallback(async (consoCode: string) => {
    const res = await fetchConsoDetail(consoCode);
    if (res) {
      console.log(res);
      setByPickOrderRows(res.pickOrders)
      setByItemsRows(res.items)
    } else {
      console.log("error");
      console.log(res);
    }
  }, []);

  useEffect(() => {
    if (consoCode) {
      fetchConso(consoCode);
    }
  }, [consoCode]);
  return (
    <>
      <Grid
        container
        rowGap={1}
        // direction="column"
        alignItems="center"
        justifyContent="center"
      >
        <Grid item xs={12}>
          {isLoading ? (
            <CircularProgress size={40} />
          ) : (
            <SearchResults<ConsoPickOrderResult>
              items={filteredPickOrders}
              columns={columns}
              pagingController={pagingController}
              setPagingController={setPagingController}
              totalCount={totalCount}
            />
          )}
        </Grid>
      </Grid>
      {consoCode != undefined ? (
        <Modal open={modalOpen} onClose={closeHandler}>
          <Box sx={{ ...style, maxHeight: 800 }}>
            <Typography mb={2} variant="h4">
              {consoCode}
            </Typography>
            <Box sx={{ 
                height: 400, 
                overflowY: "auto" 
                }}>
              <Grid container>
                <Grid item xs={12} sx={{ mt: 2 }}>
                  <ConsolidatePickOrderSum
                    rows={byPickOrderRows}
                    setRows={setByPickOrderRows}
                    consoCode={consoCode}
                    revertIds={revertIds}
                    setRevertIds={setRevertIds}
                  />
                </Grid>
                <Grid item xs={12}>
                  <ConsolidatePickOrderItemSum 
                    rows={byItemsRows}
                    setRows={setByItemsRows}
                  />
                </Grid>
              </Grid>
            </Box>
            <Grid container>
              <Grid
                item
                xs={12}
                display="flex"
                justifyContent="end"
                alignItems="end"
              >
                <Button
                  disabled={(revertIds as number[]).length < 1}
                  variant="outlined"
                  onClick={handleConsolidate_revert}
                  sx={{ mr: 1 }}
                >
                  {t("remove")}
                </Button>
                <Button
                  // disabled={selectedRows.length < 1}
                  variant="outlined"
                  onClick={handleRelease}
                >
                  {t("release")}
                </Button>
              </Grid>
            </Grid>
          </Box>
        </Modal>
      ) : undefined}
    </>
  );
};

export default ConsolidatedPickOrders;
