"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useTranslation } from "react-i18next";
import {
  FormProvider,
  SubmitErrorHandler,
  SubmitHandler,
  useFieldArray,
  useForm,
} from "react-hook-form";
import {
  Box,
  Button,
  Grid,
  Link,
  Stack,
  Tab,
  Tabs,
  TabsProps,
  Typography,
} from "@mui/material";
import { Add, Check, Close, EditNote } from "@mui/icons-material";
import { useGridApiRef } from "@mui/x-data-grid";
import DetailInfoCard from "@/components/DetailedScheduleDetail/DetailInfoCard";
import ViewByFGDetails, {
  // FGRecord,
} from "@/components/DetailedScheduleDetail/ViewByFGDetails";
import { DetailedProdScheduleLineResult, DetailedProdScheduleResult, ScheduleType } from "@/app/api/scheduling";
import { releaseProdScheduleLine, saveProdScheduleLine } from "@/app/api/scheduling/actions";
import useUploadContext from "../UploadProvider/useUploadContext";
import ArrowBackIcon from '@mui/icons-material/ArrowBack';

// temp interface input
// export interface SaveDetailedSchedule {
//   id: number;
//   productionDate: string;
//   totalJobOrders: number;
//   totalProductionQty: number;
// }

type Props = {
  isEditMode: boolean;
  // type: TypeEnum;
  defaultValues: Partial<DetailedProdScheduleResult> | undefined;
  // qcChecks: ItemQc[]
  type: ScheduleType;
};

const DetailedScheduleDetailView: React.FC<Props> = ({
  isEditMode,
  // type,
  defaultValues,
  // qcChecks,
  type
}) => {
  // console.log(type)
  const apiRef = useGridApiRef();
  const params = useSearchParams();
  console.log(params.get("id"));
  const [serverError, setServerError] = useState("");
  const [tabIndex, setTabIndex] = useState(0);
  const { t } = useTranslation("schedule");
  const router = useRouter();
  const [isEdit, setIsEdit] = useState(false);
  const { setIsUploading } = useUploadContext()

  // console.log(typeId)
  const formProps = useForm<DetailedProdScheduleResult>({
    defaultValues: defaultValues
  });
  const errors = formProps.formState.errors;

  const lineFormProps = useFieldArray<DetailedProdScheduleResult>({
    control: formProps.control,
    name: "prodScheduleLines"
  })

  const handleTabChange = useCallback<NonNullable<TabsProps["onChange"]>>(
    (_e, newValue) => {
      setTabIndex(newValue);
    },
    [],
  );

  // const calNewProportion = useCallback((demandQty: number, bomOutputQty: number) => {
  //   return ((demandQty ?? 0) / (bomOutputQty ?? 1)).toFixed(2)
  // }, [])

  // const [pagingController, setPagingController] = useState({
  //   pageNum: 1,
  //   pageSize: 10,
  //   totalCount: 0,
  // });

  const handleCancel = () => {
    router.replace(`/scheduling/detailed`);
  };

  const onSubmit = useCallback<SubmitHandler<DetailedProdScheduleResult>>(
    async (data, event) => {
      const hasErrors = false;
      console.log(errors);
      // console.log(apiRef.current.getCellValue(2, "lowerLimit"))
      // apiRef.current.
      try {
        if (hasErrors) {
          setServerError(t("An error has occurred. Please try again later."));
          return false;
        }
      } catch (e) {
        // backend error
        setServerError(t("An error has occurred. Please try again later."));
        console.log(e);
      }
    },
    [apiRef, router, t],
  );

  // multiple tabs
  const onSubmitError = useCallback<SubmitErrorHandler<DetailedProdScheduleResult>>(
    (errors) => { },
    [],
  );

  const onClickEdit = () => {
    setIsEdit(!isEdit);
  };

  const onReleaseClick = useCallback(async (row: DetailedProdScheduleLineResult) => {
    setIsUploading(true)

    try {
      const response = await releaseProdScheduleLine({
        id: row.id,
        demandQty: row.demandQty
      })

      if (response) {
        const index = formProps.getValues("prodScheduleLines").findIndex(ele => ele.id == row.id)
        // console.log(index, formProps.getValues(`prodScheduleLines.${index}.approved`))
        // formProps.setValue(`prodScheduleLines.${index}.approved`, true)
        // formProps.setValue(`prodScheduleLines.${index}.jobNo`, response.code)
        formProps.setValue(`prodScheduleLines`, response.entity.prodScheduleLines.sort((a, b) => b.priority - a.priority))
        // console.log(index, formProps.getValues(`prodScheduleLines.${index}.approved`))
      }
      setIsUploading(false)
    } catch (e) {
      console.log(e)
      setIsUploading(false)
    }
  }, [])

  const [tempValue, setTempValue] = useState<string | number | null>(null)
  const onEditClick = useCallback((rowId: number) => {
    const row = formProps.getValues("prodScheduleLines").find(ele => ele.id == rowId)
    if (row) {
      setTempValue(row.demandQty)
    }
  }, [])

  const handleEditChange = useCallback((rowId: number, fieldName: keyof DetailedProdScheduleLineResult, newValue: number | string) => {
    const index = formProps.getValues("prodScheduleLines").findIndex(ele => ele.id == rowId)
    formProps.setValue(`prodScheduleLines.${index}.demandQty`, Number(newValue))
  }, [])

  const onSaveClick = useCallback(async (row: DetailedProdScheduleLineResult) => {
    setIsUploading(true)
    try {
      const response = await saveProdScheduleLine({
        id: row.id,
        demandQty: row.demandQty
      })

      if (response) {
        const index = formProps.getValues("prodScheduleLines").findIndex(ele => ele.id == row.id)
        formProps.setValue(`prodScheduleLines.${index}.bomMaterials`, response.entity.bomMaterials)
      }
      setIsUploading(false)
    } catch (e) {
      console.log(e)
      setIsUploading(false)
    }
  }, [])

  const onCancelClick = useCallback(async (rowId: number) => {
    // if (tempValue) {
      const index = formProps.getValues("prodScheduleLines").findIndex(ele => ele.id == rowId)
      formProps.setValue(`prodScheduleLines.${index}.demandQty`, Number(tempValue))
    // }
  }, [tempValue])

  return (
    <>
      <FormProvider {...formProps}>
        <Stack
          spacing={2}
          component="form"
          onSubmit={formProps.handleSubmit(onSubmit, onSubmitError)}
        >
          {/*<Grid>*/}
          {/*  <Typography mb={2} variant="h4">*/}
          {/*    {t(`${mode} ${title}`)}*/}
          {/*  </Typography>*/}
          {/*</Grid>*/}
          <DetailInfoCard
            // recordDetails={formProps.formState.defaultValues}
            // isEditing={isEdit}
            isEditing={false}
          />
          {/* <Stack
            direction="row"
            justifyContent="space-between"
            flexWrap="wrap"
            rowGap={2}
          >
            <Button
              variant="contained"
              onClick={onClickEdit}
            // startIcon={<Add />}
            //LinkComponent={Link}
            //href="qcCategory/create"
            >
              {isEdit ? t("Save") : t("Edit")}
            </Button>
          </Stack> */}

          {/* <Tabs value={tabIndex} onChange={handleTabChange} variant="scrollable">
            <Tab label={t("View By FG") + (tabIndex === 0 ? " (Selected)" : "")} iconPosition="end" />
            <Tab label={t("View By Material") + (tabIndex === 1 ? " (Selected)" : "")} iconPosition="end" />
          </Tabs> */}
          {serverError && (
            <Typography variant="body2" color="error" alignSelf="flex-end">
              {serverError}
            </Typography>
          )}
          {/* {tabIndex === 0 && <ViewByFGDetails isEdit={isEdit} apiRef={apiRef} />} */}
          <ViewByFGDetails 
            isEdit={true}
            apiRef={apiRef}
            onReleaseClick={onReleaseClick}
            onEditClick={onEditClick}
            handleEditChange={handleEditChange}
            onSaveClick={onSaveClick}
            onCancelClick={onCancelClick}
            type={type} />
          {/* {tabIndex === 1 && <ViewByBomDetails isEdit={isEdit} apiRef={apiRef} isHideButton={true} />} */}
          <Stack direction="row" justifyContent="flex-end" gap={1}>
            {/* <Button
              name="submit"
              variant="contained"
              startIcon={<Check />}
              type="submit"
            //   disabled={submitDisabled}
            >
              {isEditMode ? t("Save") : t("Confirm")}
            </Button> */}
            <Button
              variant="outlined"
              startIcon={<ArrowBackIcon />}
              onClick={handleCancel}
            >
              {t("Back")}
            </Button>
          </Stack>
        </Stack>
      </FormProvider>
    </>
  );
};
export default DetailedScheduleDetailView;
