"use client";

import { PurchaseQcResult, PurchaseQCInput } from "@/app/api/po/actions";
import {
  Box,
  Card,
  CardContent,
  Grid,
  Stack,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { useFormContext } from "react-hook-form";
import { useTranslation } from "react-i18next";
import StyledDataGrid from "../StyledDataGrid";
import { useCallback, useEffect, useMemo, useState } from "react";
import {
  GridColDef,
  GridRowIdGetter,
  GridRowModel,
  useGridApiContext,
  GridRenderCellParams,
  GridRenderEditCellParams,
  useGridApiRef,
} from "@mui/x-data-grid";
import InputDataGrid from "../InputDataGrid";
import { TableRow } from "../InputDataGrid/InputDataGrid";
import { GridEditInputCell } from "@mui/x-data-grid";
import { StockInLine } from "@/app/api/po";
import { stockInLineStatusMap } from "@/app/utils/formatUtil";
import { fetchQcItemCheck, fetchQcResult } from "@/app/api/qc/actions";
import { QcItemWithChecks } from "@/app/api/qc";
import axios from "@/app/(main)/axios/axiosInstance";
import { NEXT_PUBLIC_API_URL } from "@/config/api";
import axiosInstance from "@/app/(main)/axios/axiosInstance";
import TwoLineCell from "../PoDetail/TwoLineCell";
import QcSelect from "../PoDetail/QcSelect";
import { PickOrderQcInput } from "@/app/api/pickOrder/actions";

interface Props {
  qcDefaultValues: PickOrderQcInput;
  qc: QcItemWithChecks[];
  disabled: boolean;
}
type EntryError =
  | {
      [field in keyof PurchaseQcResult]?: string;
    }
  | undefined;

type PoQcRow = TableRow<Partial<PurchaseQcResult>, EntryError>;
// fetchQcItemCheck
const QcContent: React.FC<Props> = ({ qc, qcDefaultValues, disabled }) => {
  const { t } = useTranslation("purchaseOrder");
  const apiRef = useGridApiRef();
  const {
    register,
    formState: { errors, defaultValues, touchedFields },
    watch,
    control,
    setValue,
    getValues,
    reset,
    resetField,
    setError,
    clearErrors,
  } = useFormContext<PickOrderQcInput>();
  console.log(qcDefaultValues);
  console.log(defaultValues);

  //// validate form
  const accQty = watch("qty");
  const validateForm = useCallback(() => {
    console.log(accQty);
    if (accQty > qcDefaultValues.qty) {
      setError("qty", {
        message: `${t("qty must not greater than")} ${qcDefaultValues.qty}`,
        type: "required",
      });
    }
    if (accQty < 1) {
      setError("qty", {
        message: t("minimal value is 1"),
        type: "required",
      });
    }
    if (isNaN(accQty)) {
      setError("qty", {
        message: t("value must be a number"),
        type: "required",
      });
    }
  }, [accQty]);

  useEffect(() => {
    clearErrors();
    validateForm();
  }, [validateForm]);
  // const [recordQty, setRecordQty] = useState(0);
  const columns = useMemo<GridColDef[]>(
    () => [
      {
        field: "qcItemId",
        headerName: t("qc Check"),
        flex: 1,
        editable: !disabled,
        valueFormatter(params) {
          const row = params.id ? params.api.getRow<PoQcRow>(params.id) : null;
          if (!row) {
            return null;
          }
          const Qc = qc.find((q) => q.id === row.qcItemId);
          return Qc ? `${Qc.code} - ${Qc.name}` : t("Please select QC");
        },
        renderCell(params: GridRenderCellParams<PoQcRow, number>) {
          console.log(params.value);
          return <TwoLineCell>{params.formattedValue}</TwoLineCell>;
        },
        renderEditCell(params: GridRenderEditCellParams<PoQcRow, number>) {
          const errorMessage =
            params.row._error?.[params.field as keyof PurchaseQcResult];
          console.log(errorMessage);
          const content = (
            <QcSelect
              allQcs={qc}
              value={params.row.qcItemId}
              onQcSelect={async (qcItemId) => {
                await params.api.setEditCellValue({
                  id: params.id,
                  field: "qcItemId",
                  value: qcItemId,
                });
                // await params.api.setEditCellValue({
                //   id: params.id,
                //   field: "type",
                //   value: "determine1",
                // });
              }}
            />
          );
          return errorMessage ? (
            <Tooltip title={errorMessage}>
              <Box width="100%">{content}</Box>
            </Tooltip>
          ) : (
            content
          );
        },
      },
      {
        field: "failQty",
        headerName: t("failQty"),
        flex: 1,
        editable: !disabled,
        type: "number",
        renderEditCell(params: GridRenderEditCellParams<PoQcRow>) {
          // const recordQty = params.row.qty
          // if (recordQty !== undefined) {
          //   setUnrecordQty((prev) => prev - recordQty)
          // }
          const errorMessage =
            params.row._error?.[params.field as keyof PurchaseQcResult];
          const content = <GridEditInputCell {...params} />;
          return errorMessage ? (
            <Tooltip title={t(errorMessage)}>
              <Box width="100%">{content}</Box>
            </Tooltip>
          ) : (
            content
          );
        },
      },
    ],
    [qc],
  );
  /// validate datagrid
  const validation = useCallback(
    (newRow: GridRowModel<PoQcRow>): EntryError => {
      const error: EntryError = {};
      const { qcItemId, failQty } = newRow;
      if (!qcItemId || qcItemId <= 0) {
        error["qcItemId"] = t("select qc");
      }
      if (!failQty || failQty <= 0) {
        error["failQty"] = t("enter a failQty");
      }
      if (failQty && failQty > qcDefaultValues.qty) {
        error["failQty"] = t("qty too big");
      }
      return Object.keys(error).length > 0 ? error : undefined;
    },
    [],
  );

  return (
    <Grid container justifyContent="flex-start" alignItems="flex-start">
      <Grid item xs={12}>
        <Typography variant="h6" display="block" marginBlockEnd={1}>
          {t("Qc Detail")}
        </Typography>
      </Grid>
      <Grid
        container
        justifyContent="flex-start"
        alignItems="flex-start"
        spacing={2}
        sx={{ mt: 0.5 }}
      >
        <Grid item xs={12} lg={12}>
          <TextField
            label={t("accepted Qty")}
            fullWidth
            // value={qcDefaultValues.qty}
            {...register("qty", {
              required: "qty required!",
              valueAsNumber: true,
              max: qcDefaultValues.qty,
            })}
            disabled={disabled}
            error={Boolean(errors.qty)}
            helperText={errors.qty?.message}
          />
        </Grid>
      </Grid>
      <Grid
        container
        justifyContent="flex-start"
        alignItems="flex-start"
        spacing={2}
        sx={{ mt: 0.5 }}
      >
        <Grid item xs={12}>
          <InputDataGrid<PickOrderQcInput, PurchaseQcResult, EntryError>
            apiRef={apiRef}
            checkboxSelection={false}
            _formKey={"qcResult"}
            columns={columns}
            validateRow={validation}
            needAdd={!disabled}
          />
        </Grid>
      </Grid>
    </Grid>
  );
};
export default QcContent;
