"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";
// NOTE: Assuming 'releaseProdSchedule' is the new action function 
// you need to implement to call the '/productionSchedule/detail/detailed/release' API
import { releaseProdScheduleLine, saveProdScheduleLine, releaseProdSchedule } 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();
  const scheduleId = params.get("id"); // Get the schedule ID for the global release API
  console.log(scheduleId);
  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 { reset, handleSubmit, setValue, getValues } = formProps

  useEffect(() => {
    if (defaultValues) {
      reset(defaultValues);
    }
  }, [defaultValues, reset]);

  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) {
        // Find index of the updated line to refresh its data
        // const index = formProps.getValues("prodScheduleLines").findIndex(ele => ele.id == row.id)
        
        // Update the entire line array, assuming the backend returns the updated list
        formProps.setValue(`prodScheduleLines`, response.entity.prodScheduleLines.sort((a, b) => b.priority - a.priority))
      }
      setIsUploading(false)
    } catch (e) {
      console.log(e)
      setIsUploading(false)
    }
  }, [formProps, setIsUploading])

  // --- NEW FUNCTION: GLOBAL RELEASE FOR THE ENTIRE SCHEDULE ---
  // --- UPDATED FUNCTION: GLOBAL RELEASE WITH produceAt CHECK ---
  const onGlobalReleaseClick = useCallback(async () => {
    if (!scheduleId) {
      setServerError(t("Cannot release. Schedule ID is missing."));
      return;
    }

    // 1. Get the production date (produceAt) from the form values
    const produceAtValue = getValues("produceAt");

    if (produceAtValue) {
      // Use standard JS Date comparison for YYYY-MM-DD
      const today = new Date().toISOString().split('T')[0];
      
      // Handle various potential formats (string or array from API)
      let scheduleDate = "";
      if (Array.isArray(produceAtValue)) {
        // If it's an array format [YYYY, MM, DD] common in Java backends
        const [year, month, day] = produceAtValue;
        scheduleDate = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
      } else {
        scheduleDate = new Date(produceAtValue).toISOString().split('T')[0];
      }

      // 2. Alert and block if the date is not today
      if (scheduleDate !== today) {
        alert(t("Only schedules for today can be released.")); 
        return;
      }
    }

    setIsUploading(true);
    setServerError("");

    try {
      const response = await releaseProdSchedule({
        id: Number(scheduleId),
      });

      if (response) {
        router.refresh();
      }
    } catch (e) {
      console.error(e);
      setServerError(t("An unexpected error occurred during global schedule release."));
    } finally {
      setIsUploading(false);
    }
  }, [scheduleId, setIsUploading, t, router, getValues]);
  // --------------------------------------------------------------------
  
  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)
    }
  }, [formProps])

  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))
  }, [formProps])

  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)
        // Update BOM materials for the line after saving demand quantity
        formProps.setValue(`prodScheduleLines.${index}.bomMaterials`, response.entity.bomMaterials)
      }
      setIsUploading(false)
    } catch (e) {
      console.log(e)
      setIsUploading(false)
    }
  }, [formProps, setIsUploading])

  const onCancelClick = useCallback(async (rowId: number) => {
    // Revert the demandQty to the temporary value stored on EditClick
    if (tempValue !== null) {
      const index = formProps.getValues("prodScheduleLines").findIndex(ele => ele.id == rowId)
      formProps.setValue(`prodScheduleLines.${index}.demandQty`, Number(tempValue))
    }
  }, [formProps, 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}
             >
               {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}>
            
            {/* --- NEW BUTTON: Release Entire Schedule --- */}
            <Button
              variant="contained"
              startIcon={<Check />}
              onClick={onGlobalReleaseClick}
              disabled={!scheduleId} // Disable if we don't have a schedule ID
            >
              {t("Generate Job Order")}
            </Button>
            {/* ------------------------------------------- */}

            {/* <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;