"use client";

import { PurchaseQcResult, PurchaseQCInput } from "@/app/api/po/actions";
import {
  Autocomplete,
  Box,
  Card,
  CardContent,
  FormControl,
  Grid,
  Stack,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { Controller, 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 { INPUT_DATE_FORMAT, 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 { SavePickOrderLineRequest, SavePickOrderRequest } from "@/app/api/pickOrder/actions";
import TwoLineCell from "../PoDetail/TwoLineCell";
import ItemSelect from "./ItemSelect";
import { ItemCombo } from "@/app/api/settings/item/actions";
import { DatePicker, LocalizationProvider } from "@mui/x-date-pickers";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import dayjs from "dayjs";

interface Props {
  items: ItemCombo[];
//   disabled: boolean;
}
type EntryError =
  | {
      [field in keyof SavePickOrderLineRequest]?: string;
    }
  | undefined;

type PolRow = TableRow<Partial<SavePickOrderLineRequest>, EntryError>;
// fetchQcItemCheck
const CreateForm: React.FC<Props> = ({ items }) => {
  const { 
    t,
    i18n: { language },
   } = useTranslation("pickOrder");
  const apiRef = useGridApiRef();
  const {
    formState: { errors, defaultValues, touchedFields },
    watch,
    control,
    setValue,
  } = useFormContext<SavePickOrderRequest>();
  console.log(defaultValues);
  const targetDate = watch("targetDate");
  
//// 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();
//   }, [clearErrors, validateForm]);

  const columns = useMemo<GridColDef[]>(
    () => [
      {
        field: "itemId",
        headerName: t("Item"),
        // width: 100,
        flex: 1,
        editable: true,
        valueFormatter(params) {
          const row = params.id ? params.api.getRow<PolRow>(params.id) : null;
          if (!row) {
            return null;
          }
          const Item = items.find((q) => q.id === row.itemId);
          return Item ? Item.label : t("Please select item");
        },
        renderCell(params: GridRenderCellParams<PolRow, number>) {
          console.log(params.value);
          return <TwoLineCell>{params.formattedValue}</TwoLineCell>;
        },
        renderEditCell(params: GridRenderEditCellParams<PolRow, number>) {
          const errorMessage =
            params.row._error?.[params.field as keyof SavePickOrderLineRequest];
          console.log(errorMessage);
          const content = (
            // <></>
            <ItemSelect
              allItems={items}
              value={params.row.itemId}
              onItemSelect={async (itemId, uom, uomId) => {
                console.log(uom)
                await params.api.setEditCellValue({
                  id: params.id,
                  field: "itemId",
                  value: itemId,
                });
                await params.api.setEditCellValue({
                  id: params.id,
                  field: "uom",
                  value: uom
                })
                await params.api.setEditCellValue({
                  id: params.id,
                  field: "uomId",
                  value: uomId
                })
              }}
            />
          );
          return errorMessage ? (
            <Tooltip title={errorMessage}>
              <Box width="100%">{content}</Box>
            </Tooltip>
          ) : (
            content
          );
        },
      },
      {
        field: "qty",
        headerName: t("qty"),
        // width: 100,
        flex: 1,
        type: "number",
        editable: true,
        renderEditCell(params: GridRenderEditCellParams<PolRow>) {
          const errorMessage =
            params.row._error?.[params.field as keyof SavePickOrderLineRequest];
          const content = <GridEditInputCell {...params} />;
          return errorMessage ? (
            <Tooltip title={t(errorMessage)}>
              <Box width="100%">{content}</Box>
            </Tooltip>
          ) : (
            content
          );
        },
      },
      {
        field: "uom",
        headerName: t("uom"),
        // width: 100,
        flex: 1,
        editable: true,
        // renderEditCell(params: GridRenderEditCellParams<PolRow>) {
        //   console.log(params.row)
        //   const errorMessage =
        //     params.row._error?.[params.field as keyof SavePickOrderLineRequest];
        //   const content = <GridEditInputCell {...params} />;
        //   return errorMessage ? (
        //     <Tooltip title={t(errorMessage)}>
        //       <Box width="100%">{content}</Box>
        //     </Tooltip>
        //   ) : (
        //     content
        //   );
        // }
      }
    ],
    [items, t],
  );
  /// validate datagrid
  const validation = useCallback(
    (newRow: GridRowModel<PolRow>): EntryError => {
      const error: EntryError = {};
      const { itemId, qty } = newRow;
      if (!itemId || itemId <= 0) {
        error["itemId"] = t("select qc");
      }
      if (!qty || qty <= 0) {
        error["qty"] = t("enter a qty");
      }
      return Object.keys(error).length > 0 ? error : undefined;
    },
    [],
  );

  const typeList = [
    {
      type: "Consumable"
    }
  ]

  const onChange = useCallback(
    (event: React.SyntheticEvent, newValue: {type: string}) => {
      console.log(newValue);
      setValue("type", newValue.type);
    },
    [setValue],
  );

  return (
    <Grid container justifyContent="flex-start" alignItems="flex-start">
      <Grid item xs={12}>
        <Typography variant="h6" display="block" marginBlockEnd={1}>
          {t("Pick Order Detail")}
        </Typography>
      </Grid>
      <Grid
        container
        justifyContent="flex-start"
        alignItems="flex-start"
        spacing={2}
        sx={{ mt: 0.5 }}
      >
        <Grid item xs={6} lg={6}>
            <FormControl fullWidth>
              <Autocomplete
                disableClearable
                fullWidth
                getOptionLabel={(option) => option.type}
                options={typeList}
                onChange={onChange}
                renderInput={(params) => <TextField {...params} label={t("type")}/>}
              />
            </FormControl>
        </Grid>
        <Grid item xs={6}>
            <Controller
              control={control}
              name="targetDate"
              // rules={{ required: !Boolean(productionDate) }}
              render={({ field }) => {
                return (
                  <LocalizationProvider
                    dateAdapter={AdapterDayjs}
                    adapterLocale={`${language}-hk`}
                  >
                    <DatePicker
                      {...field}
                      sx={{ width: "100%" }}
                      label={t("targetDate")}
                      value={targetDate ? dayjs(targetDate) : undefined}
                      onChange={(date) => {
                        console.log(date);
                        if (!date) return;
                        console.log(date.format(INPUT_DATE_FORMAT));
                        setValue("targetDate", date.format(INPUT_DATE_FORMAT));
                        // field.onChange(date);
                      }}
                      inputRef={field.ref}
                      slotProps={{
                        textField: {
                          // required: true,
                          error: Boolean(errors.targetDate?.message),
                          helperText: errors.targetDate?.message,
                        },
                      }}
                    />
                  </LocalizationProvider>
                );
              }}
            />
          </Grid>
      </Grid>
      <Grid
        container
        justifyContent="flex-start"
        alignItems="flex-start"
        spacing={2}
        sx={{ mt: 0.5 }}
      >
        <Grid item xs={12}>
          <InputDataGrid<SavePickOrderRequest, SavePickOrderLineRequest, EntryError>
            apiRef={apiRef}
            checkboxSelection={false}
            _formKey={"pickOrderLine"}
            columns={columns}
            validateRow={validation}
            needAdd={true}
          />
        </Grid>
      </Grid>
    </Grid>
  );
};
export default CreateForm;
