"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 TwoLineCell from "./TwoLineCell";
import QcSelect from "./QcSelect";
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";

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

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

  //// validate form
  const accQty = watch("acceptedQty");
  const validateForm = useCallback(() => {
    console.log(accQty);
    if (accQty > itemDetail.acceptedQty) {
      setError("acceptedQty", {
        message: `${t("acceptedQty must not greater than")} ${itemDetail.acceptedQty}`,
        type: "required",
      });
    }
    if (accQty < 1) {
      setError("acceptedQty", {
        message: t("minimal value is 1"),
        type: "required",
      });
    }
    if (isNaN(accQty)) {
      setError("acceptedQty", {
        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 > itemDetail.acceptedQty) {
        error["failQty"] = t("qty too big");
      }
      return Object.keys(error).length > 0 ? error : undefined;
    },
    []
  );

  useEffect(() => {
    console.log(itemDetail);
    var status = "receiving";
    // switch (itemDetail.status) {
    //   case 'pending':
    //     status = "receiving"
    //     break;
    // }
    setValue("status", status);
  }, [itemDetail]);

  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={itemDetail.acceptedQty}
            {...register("acceptedQty", {
              required: "acceptedQty required!",
              valueAsNumber: true,
              max: itemDetail.acceptedQty,
            })}
            disabled={disabled}
            error={Boolean(errors.acceptedQty)}
            helperText={errors.acceptedQty?.message}
          />
        </Grid>
        {/* <Grid item xs={12} lg={6}>
          <TextField
            label={t("Total record qty")}
            fullWidth
            value={recordQty}
            disabled
            // {...register("sampleRate", {
            //   required: "sampleRate required!",
            // })}
            // error={Boolean(errors.sampleRate)}
            // helperText={errors.sampleRate?.message}
          />
        </Grid> */}
        <Grid item xs={12} lg={6}>
          <TextField
            label={t("sampleRate")}
            fullWidth
            // defaultValue={1}
            {...register("sampleRate", {
              required: "sampleRate required!",
              valueAsNumber: true,
            })}
            disabled={disabled}
            error={Boolean(errors.sampleRate)}
            helperText={errors.sampleRate?.message}
          />
        </Grid>
        <Grid item xs={12} lg={6}>
          <TextField
            label={t("sampleWeight")}
            fullWidth
            // defaultValue={1}
            {...register("sampleWeight", {
              required: "sampleWeight required!",
              valueAsNumber: true,
            })}
            disabled={disabled}
            error={Boolean(errors.sampleWeight)}
            helperText={errors.sampleWeight?.message}
          />
        </Grid>
        <Grid item xs={12} lg={6}>
          <TextField
            label={t("totalWeight")}
            fullWidth
            // defaultValue={1}
            {...register("totalWeight", {
              required: "totalWeight required!",
              valueAsNumber: true,
            })}
            disabled={disabled}
            error={Boolean(errors.totalWeight)}
            helperText={errors.totalWeight?.message}
          />
        </Grid>
      </Grid>
      <Grid
        container
        justifyContent="flex-start"
        alignItems="flex-start"
        spacing={2}
        sx={{ mt: 0.5 }}
      >
        <Grid item xs={12}>
          <InputDataGrid<PurchaseQCInput, PurchaseQcResult, EntryError>
            apiRef={apiRef}
            checkboxSelection={false}
            _formKey={"qcResult"}
            columns={columns}
            validateRow={validation}
            needAdd={
              itemDetail.status === "qc" || itemDetail.status === "pending"
            }
          />
        </Grid>
      </Grid>
    </Grid>
  );
};
export default QcForm;
