import {
  Autocomplete,
  Box,
  Button,
  CircularProgress,
  FormControl,
  Grid,
  Modal,
  ModalProps,
  TextField,
  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,
  releasePickOrder,
  ReleasePickOrderInputs,
} from "@/app/api/pickOrder/actions";
import { EditNote } from "@mui/icons-material";
import { fetchNameList, NameList } from "@/app/api/user/actions";
import { useField } from "@mui/x-date-pickers/internals";
import {
  FormProvider,
  SubmitErrorHandler,
  SubmitHandler,
  useForm,
} from "react-hook-form";
import { pickOrderStatusMap } from "@/app/utils/formatUtil";

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,
  width: { xs: "100%", sm: "100%", md: "100%" },
};
interface DisableButton {
  releaseBtn: boolean;
  removeBtn: boolean;
}

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 [usernameList, setUsernameList] = useState<NameList[]>([]);

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

  const formProps = useForm<ReleasePickOrderInputs>();
  const errors = formProps.formState.errors;

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

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

  const onDetailClick = useCallback(
    (pickOrder: any) => {
      console.log(pickOrder);
      const status = pickOrder.status;
      if (pickOrderStatusMap[status] >= 3) {
        router.push(`/pickOrder/detail?consoCode=${pickOrder.consoCode}`);
      } else {
        openDetailModal(pickOrder.consoCode);
      }
    },
    [router, openDetailModal],
  );
  const columns = useMemo<Column<ConsoPickOrderResult>[]>(
    () => [
      {
        name: "id",
        label: t("Detail"),
        onClick: onDetailClick,
        buttonIcon: <EditNote />,
      },
      {
        name: "consoCode",
        label: t("consoCode"),
      },
      {
        name: "status",
        label: t("status"),
      },
    ],
    [onDetailClick, t],
  );
  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 isReleasable = useCallback((itemList: ByItemsSummary[]): boolean => {
    let isReleasable = true;
    for (const item of itemList) {
      isReleasable = item.requiredQty >= item.availableQty;
      if (!isReleasable) return isReleasable;
    }
    return isReleasable;
  }, []);

  const fetchConso = useCallback(
    async (consoCode: string) => {
      const res = await fetchConsoDetail(consoCode);
      const nameListRes = await fetchNameList();
      if (res) {
        console.log(res);
        setByPickOrderRows(res.pickOrders);
        // for testing
        // for (const item of res.items) {
        //   item.availableQty = 1000;
        // }
        setByItemsRows(res.items);
        setDisableRelease(isReleasable(res.items));
      } else {
        console.log("error");
        console.log(res);
      }
      if (nameListRes) {
        console.log(nameListRes);
        setUsernameList(nameListRes);
      }
    },
    [isReleasable],
  );

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

  const onChange = useCallback(
    (event: React.SyntheticEvent, newValue: NameList) => {
      console.log(newValue);
      formProps.setValue("assignTo", newValue.id);
    },
    [formProps],
  );

  const onSubmit = useCallback<SubmitHandler<ReleasePickOrderInputs>>(
    async (data, event) => {
      console.log(data);
      try {
        const res = await releasePickOrder(data);
        console.log(res);
        if (res.consoCode.length > 0) {
          console.log(res);
          router.push(`/pickOrder/detail?consoCode=${res.consoCode}`);
        } else {
          console.log(res);
        }
      } catch (error) {
        console.log(error);
      }
    },
    [router],
  );
  const onSubmitError = useCallback<SubmitErrorHandler<ReleasePickOrderInputs>>(
    (errors) => {},
    [],
  );

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

  useEffect(() => {
    if (consoCode) {
      fetchConso(consoCode);
      formProps.setValue("consoCode", consoCode);
    }
  }, [consoCode, fetchConso, formProps]);

  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}>
          <FormProvider {...formProps}>
            <Box
              sx={{ ...style, maxHeight: 800 }}
              component="form"
              onSubmit={formProps.handleSubmit(onSubmit, onSubmitError)}
            >
              <Grid container>
                <Grid item xs={8}>
                  <Typography mb={2} variant="h4">
                    {consoCode}
                  </Typography>
                </Grid>
                <Grid
                  item
                  xs={4}
                  display="flex"
                  justifyContent="end"
                  alignItems="end"
                >
                  <FormControl fullWidth>
                    <Autocomplete
                      disableClearable
                      fullWidth
                      getOptionLabel={(option) => option.name}
                      options={usernameList}
                      onChange={onChange}
                      renderInput={(params) => <TextField {...params} />}
                    />
                  </FormControl>
                </Grid>
              </Grid>
              <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={disableRelease}
                    variant="outlined"
                    //   onClick={handleRelease}
                    type="submit"
                  >
                    {t("release")}
                  </Button>
                </Grid>
              </Grid>
            </Box>
          </FormProvider>
        </Modal>
      ) : undefined}
    </>
  );
};

export default ConsolidatedPickOrders;
