"use client";

import { PurchaseQcCheck, 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, 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 { QcItemWithChecks } from "@/app/api/qc";
import { GridEditInputCell } from "@mui/x-data-grid";
import { StockInLine } from "@/app/api/po";

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

type PoQcRow = TableRow<Partial<PurchaseQcCheck>, EntryError>;

const QcForm: React.FC<Props> = ({ 
  qc,
  itemDetail,
 }) => {
  const { t } = useTranslation();
  const apiRef = useGridApiRef();
  const {
    register,
    formState: { errors, defaultValues, touchedFields },
    watch,
    control,
    setValue,
    getValues,
    reset,
    resetField,
    setError,
    clearErrors,
  } = useFormContext<PurchaseQCInput>();
  console.log(itemDetail)
  const [recordQty, setRecordQty] = useState(0)
  const columns = useMemo<GridColDef[]>(
    () => [
      {
        field: "qcCheckId",
        headerName: "qc Check",
        flex: 1,
        editable: true,
        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.qcCheckId);
          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 PurchaseQcCheck];
          console.log(errorMessage);
          const content = (
            <QcSelect
              allQcs={qc}
              value={params.row.qcCheckId}
              onQcSelect={async (qcCheckId) => {
                await params.api.setEditCellValue({
                  id: params.id,
                  field: "qcCheckId",
                  value: qcCheckId,
                });
              }}
            />
          );
          return errorMessage ? (
            <Tooltip title={t(errorMessage)}>
              <Box width="100%">{content}</Box>
            </Tooltip>
          ) : (
            content
          );
        },
      },
      {
        field: "qty",
        headerName: "qty",
        flex: 1,
        editable: true,
        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 PurchaseQcCheck];
          const content = <GridEditInputCell {...params} />;
          return errorMessage ? (
            <Tooltip title={t(errorMessage)}>
              <Box width="100%">{content}</Box>
            </Tooltip>
          ) : (
            content
          );
        },
      },
    ],
    []
  );
  const validation = useCallback(
    (newRow: GridRowModel<PoQcRow>): EntryError => {
      const error: EntryError = {};
      const { qcCheckId, qty } = newRow;
      if (!qcCheckId || qcCheckId <= 0) {
        error["qcCheckId"] = "select qc";
      }
      if (!qty || qty <= 0) {
        error["qty"] = "enter a qty";
      }
      if (qty && qty > itemDetail.acceptedQty) {
        error["qty"] = "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={6}>
          <TextField
            label={t("Total qty")}
            fullWidth
            value={itemDetail.acceptedQty}
            disabled
            // {...register("sampleRate", {
            //   required: "sampleRate required!",
            // })}
            // error={Boolean(errors.sampleRate)}
            // helperText={errors.sampleRate?.message}
          />
          </Grid>
        <Grid item xs={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={4}>
          <TextField
            label={t("sampleRate")}
            fullWidth
            {...register("sampleRate", {
              required: "sampleRate required!",
            })}
            error={Boolean(errors.sampleRate)}
            helperText={errors.sampleRate?.message}
          />
        </Grid>
        <Grid item xs={4}>
          <TextField
            label={t("sampleWeight")}
            fullWidth
            {...register("sampleWeight", {
              required: "sampleWeight required!",
            })}
            error={Boolean(errors.sampleWeight)}
            helperText={errors.sampleWeight?.message}
          />
        </Grid>
        <Grid item xs={4}>
          <TextField
            label={t("totalWeight")}
            fullWidth
            {...register("totalWeight", {
              required: "totalWeight required!",
            })}
            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, PurchaseQcCheck, EntryError>
            apiRef={apiRef}
            checkboxSelection={false}
            _formKey={"qcCheck"}
            columns={columns}
            validateRow={validation}
          />
        </Grid>
      </Grid>
    </Grid>
  );
};
export default QcForm;
