"use client";

import { CreateItemInputs } from "@/app/api/settings/item/actions";
import {
  GridColDef,
  GridRowModel,
  GridRenderEditCellParams,
  GridEditInputCell,
  GridRowSelectionModel,
  useGridApiRef,
} from "@mui/x-data-grid";
import { MutableRefObject, useCallback, useMemo } from "react";
import { useFormContext } from "react-hook-form";
import { useTranslation } from "react-i18next";
import InputDataGrid, { TableRow } from "../InputDataGrid/InputDataGrid";
import { Box, Grid, Tooltip } from "@mui/material";
import { ItemQc } from "@/app/api/settings/item";
import { QcChecksInputs } from "@/app/api/settings/qcCheck/actions";
import { GridApiCommunity } from "@mui/x-data-grid/internals";
import { RiceBowl } from "@mui/icons-material";

type Props = {
  apiRef: MutableRefObject<GridApiCommunity>;
};
type EntryError =
  | {
      [field in keyof QcChecksInputs]?: string;
    }
  | undefined;

type QcRow = TableRow<Partial<QcChecksInputs>, EntryError>;
const QcDetails: React.FC<Props> = ({ apiRef }) => {
  const {
    t,
    i18n: { language },
  } = useTranslation("items");

  const {
    register,
    formState: { errors, defaultValues, touchedFields },
    watch,
    control,
    setValue,
    getValues,
    reset,
    resetField,
    setError,
    clearErrors,
  } = useFormContext<CreateItemInputs>();
  //   const apiRef = useGridApiRef();
  const qcColumns = useMemo<GridColDef[]>(
    () => [
      {
        field: "name",
        headerName: t("name"),
        flex: 1,
        // editable: true,
      },
      {
        field: "code",
        headerName: t("code"),
        flex: 1,
        // editable: true,
      },
      {
        field: "description",
        headerName: t("description"),
        flex: 1,
        // editable: true,
      },
      {
        field: "instruction",
        headerName: t("instruction"),
        flex: 1,
        editable: true,
      },
      {
        field: "lowerLimit",
        headerName: t("lowerLimit"),
        flex: 1,
        editable: true,
        type: "number",
        renderEditCell(params: GridRenderEditCellParams<QcRow>) {
          const errorMessage =
            params.row._error?.[params.field as keyof QcChecksInputs];
          const content = (
            <GridEditInputCell
              {...params}
              // inputProps={{ min: 0 }}
            />
          );
          return errorMessage ? (
            <Tooltip title={t(errorMessage)}>
              <Box width="100%">{content}</Box>
            </Tooltip>
          ) : (
            content
          );
        },
      },
      {
        field: "upperLimit",
        headerName: t("upperLimit"),
        flex: 1,
        editable: true,
        type: "number",
        renderEditCell(params: GridRenderEditCellParams<QcRow>) {
          const errorMessage =
            params.row._error?.[params.field as keyof QcChecksInputs];
          const content = (
            <GridEditInputCell
              {...params}
              // inputProps={{ min: 0 }}
            />
          );
          return errorMessage ? (
            <Tooltip title={t(errorMessage)}>
              <Box width="100%">{content}</Box>
            </Tooltip>
          ) : (
            content
          );
        },
      },
    ],
    [],
  );

  const validationTest = useCallback(
    (
      newRow: GridRowModel<TableRow<Partial<QcChecksInputs>, EntryError>>,
      //   rowModel: GridRowSelectionModel
    ): EntryError => {
      const error: EntryError = {};
      console.log(newRow);
      if (!newRow.lowerLimit) {
        error["lowerLimit"] = "lower limit cannot be null";
      }
      //   if (rowModel.find(r => r == newRow.id)) {

      //   }
      if (
        newRow.lowerLimit &&
        newRow.upperLimit &&
        newRow.lowerLimit > newRow.upperLimit
      ) {
        error["lowerLimit"] =
          "lower limit should not be greater than upper limit";
        error["upperLimit"] =
          "lower limit should not be greater than upper limit";
      }
      return Object.keys(error).length > 0 ? error : undefined;
    },
    [],
  );

  return (
    <Grid container>
      <Grid item xs={12}>
        <InputDataGrid<CreateItemInputs, QcChecksInputs, EntryError>
          apiRef={apiRef}
          checkboxSelection={true}
          _formKey={"qcChecks"}
          columns={qcColumns}
          validateRow={validationTest}
        />
      </Grid>
    </Grid>
  );
};
export default QcDetails;
