"use client";

import {
  Box, Card, CardContent, Checkbox, Collapse, FormControl,
  FormControlLabel, Grid, Radio, RadioGroup, Stack, Tab,
  Tabs, TabsProps, TextField, Tooltip, Typography,
} from "@mui/material";
import { useFormContext, Controller, FieldPath } from "react-hook-form";
import { useTranslation } from "react-i18next";
import StyledDataGrid from "../StyledDataGrid";
import { Dispatch, SetStateAction, useCallback, useEffect, useMemo, useState } from "react";
import {
  GridColDef,
  useGridApiContext,
  GridRenderEditCellParams,
  useGridApiRef,
} from "@mui/x-data-grid";
import { QcFormInput, QcResult } from "@/app/api/qc";

interface Props {
  rows: QcResult[];
  disabled?: boolean;
  /** When true, use smaller font and padding (e.g. for productionProcess / tablet). */
  denseLayout?: boolean;
}

const QcForm: React.FC<Props> = ({ rows, disabled = false, denseLayout = false }) => {
  const { t } = useTranslation("purchaseOrder");
  const apiRef = useGridApiRef();
  const {
    register,
    formState: { errors, defaultValues, touchedFields },
    watch,
    control,
    setValue,
    getValues,
    reset,
    resetField,
    setError,
    clearErrors,
  } = useFormContext<QcFormInput>();

  const qcDisabled = (row : QcResult) => {
    return disabled || isExist(row.escalationLogId);
  };

  const isExist = (data : string | number | undefined) => {
    return (data !== null && data !== undefined);
  }

  function BooleanEditCell(params: GridRenderEditCellParams) {
    const apiRef = useGridApiContext();
    const { id, field, value } = params;

    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
      apiRef.current.setEditCellValue({ id, field, value: e.target.checked });
      apiRef.current.stopCellEditMode({ id, field }); // commit immediately
    };

    return <Checkbox checked={!!value} onChange={handleChange} sx={{ p: 0 }} />;
  }

  const qcColumns: GridColDef[] = useMemo(() => [
     {
      field: "name",
      headerName: t("qcItem"),
      wrapText: true,
      flex: 2.5,
      renderCell: (params) => {
        const index = getRowIndex(params);//params.api.getRowIndexRelativeToVisibleRows(params.id);
        return (
        <Box
          sx={{
            lineHeight: 1.5,
            padding: denseLayout ? "2px" : "4px",
            fontSize: denseLayout ? 14 : 18,
          }}
        >
          <b>{`${params.row.order ?? "N/A"}. ${params.value}`}</b><br/>
          {params.row.description}
        </Box>
      )},
     },
     {
      field: 'qcResult',
      headerName: t("qcResult"),
      flex: 1,
      renderCell: (params) => {
        const rowValue = params.row;
        const index = getRowIndex(params);//params.api.getRowIndexRelativeToVisibleRows(params.row.id);
        // const index = Number(params.id);
        // const index = Number(params.row.order - 1);
        // console.log(rowValue.row);
        return (
          <FormControl>
            <RadioGroup
                row
                aria-labelledby="demo-radio-buttons-group-label"
                // defaultValue={""}
                value={rowValue.qcPassed === undefined ? "" : (rowValue.qcPassed ? "true" : "false")}
                onChange={(e) => {
                  const value = (e.target.value === "true");
                  // setQcItems((prev) =>
                  //   prev.map((r): QcData => (r.id === params.id ? { ...r, qcPassed: value === "true" } : r))
                  // );
                  setValue(`qcResult.${index}.qcPassed`, value);
                }}
                name={`qcPassed-${params.id}`}
            >
                <FormControlLabel 
                  value="true" 
                  control={<Radio />} 
                  label="合格"
                  disabled={qcDisabled(rowValue)}
                  sx={{
                    color: rowValue.qcPassed === true ? "green" : "inherit",
                    "& .Mui-checked": {color: "green"}
                  }}
                />
                <FormControlLabel 
                  value="false" 
                  control={<Radio />} 
                  label="不合格" 
                  disabled={qcDisabled(rowValue)}
                  sx={{
                    color: rowValue.qcPassed === false ? "red" : "inherit",
                    "& .Mui-checked": {color: "red"}
                  }}
                />
            </RadioGroup>
          </FormControl>
        );
      },
    },
     {
      field: "failQty",
      headerName: t("failedQty"),
      flex: 0.8,
      // editable: true,
      renderCell: (params) => {
        const index = getRowIndex(params);//params.api.getRowIndexRelativeToVisibleRows(params.id);
        // const index = Number(params.id);
        return (
        <TextField
          type="number"
          size={denseLayout ? "small" : "medium"}
          value={!params.row.qcPassed? params.value : '0'}
          disabled={params.row.qcPassed || qcDisabled(params.row)}
          /* TODO improve */
          /* Reference: https://grok.com/share/c2hhcmQtNA%3D%3D_10787069-3eec-40af-a7cc-bacbdb86bf05 */
          onChange={(e) => {
            const v = e.target.value;
            const next = v === '' ? undefined : Number(v);
            if (Number.isNaN(next)) return;
            setValue(`qcResult.${index}.failQty`, next);
          }}
          // onBlur={(e) => {
          //   const v = e.target.value;
          //   const next = v === '' ? undefined : Number(v);
          //   if (Number.isNaN(next)) return;
          //   setValue(`qcResult.${index}.failQty`, next);
          // }}
          onClick={(e) => e.stopPropagation()}
          onMouseDown={(e) => e.stopPropagation()}
          onKeyDown={(e) => e.stopPropagation()}
          inputProps={{ min: 0 }}
          sx={{ width: '100%',
            "& .MuiInputBase-input": {
              padding: denseLayout ? "0.35rem 0.5rem" : "0.75rem",
              fontSize: denseLayout ? 14 : 24,
            },
          }}
        />
        );
      },
     },
     {
      field: "remarks",
      headerName: t("remarks"),
      flex: 1.7,
      renderCell: (params) => {
        // const index = Number(params.id);//params.api.getRowIndexRelativeToVisibleRows(params.id);
        const index = getRowIndex(params);//params.api.getRowIndexRelativeToVisibleRows(params.id);
        return (
          <TextField
            size="small"
            defaultValue={params.value}
            disabled={qcDisabled(params.row)}
            onBlur={(e) => {
              const value = e.target.value;
              setValue(`qcResult.${index}.remarks`, value);
            }}
            // onChange={(e) => {
            //   const remarks = e.target.value;
            //   // const next = v === '' ? undefined : Number(v);
            //   // if (Number.isNaN(next)) return;
            //   // setQcItems((prev) =>
            //   //   prev.map((r) => (r.id === params.id ? { ...r, remarks: remarks } : r))
            //   // );
            // }}
            // {...register(`qcResult.${index}.remarks`, {
            //   required: "remarks required!",
            // })}
            onClick={(e) => e.stopPropagation()}
            onMouseDown={(e) => e.stopPropagation()}
            onKeyDown={(e) => e.stopPropagation()}
            sx={{ width: '100%',
              "& .MuiInputBase-input": {
                padding: denseLayout ? "0.35rem 0.5rem" : "0.75rem",
                fontSize: denseLayout ? 14 : 24,
              },
            }}
          />
        );
      },
     },
    ], [denseLayout, t])

  // const getRowId = (row :any) => {
  //   return qcRecord.findIndex(qc => qc == row);
  //   // return row.id || `${row.name}-${Math.random().toString(36).substr(2, 9)}`;
  // };

  const getRowHeight = (row :any) => {  // Not used?
    console.log("row", row);
    if (!row.model.name) {
      return (row.model.name.length ?? 10) * 1.2 + 30;
    } else { return 60}
  };

  const getRowIndex = (params: any) => {
    return params.api.getRowIndexRelativeToVisibleRows(params.id);
    // return params.row.id;
  }

  return (
    <>
 
      <StyledDataGrid
        columns={qcColumns}
        rows={rows}
        sortModel={[]}
        getRowHeight={() => 'auto'}
        initialState={{
          pagination: { paginationModel: { page: 0, pageSize: 100 } },
        }}
        pageSizeOptions={[100]}
        slotProps={{
          pagination: {
            sx: {
              display: "none",
            },
          },
        }}
      />
    </>
  );
};
export default QcForm;
