// import {
//   Dispatch,
//   SetStateAction,
//   useCallback,
//   useEffect,
//   useMemo,
//   useState,
// } from "react";
// import StyledDataGrid from "../StyledDataGrid";
// import {
//   FooterPropsOverrides,
//   GridActionsCellItem,
//   GridCellParams,
//   GridColDef,
//   GridRowId,
//   GridRowIdGetter,
//   GridRowModel,
//   GridRowModes,
//   GridRowModesModel,
//   GridToolbarContainer,
//   GridValidRowModel,
//   useGridApiRef,
// } from "@mui/x-data-grid";
// import { useFormContext } from "react-hook-form";
// import SaveIcon from "@mui/icons-material/Save";
// import DeleteIcon from "@mui/icons-material/Delete";
// import CancelIcon from "@mui/icons-material/Cancel";
// import { Add } from "@mui/icons-material";
// import { Box, Button, Typography } from "@mui/material";
// import { useTranslation } from "react-i18next";

// export interface ResultWithId {
//   id: string | number;
// }

// export type TableRow<T extends ResultWithId, E> = Partial<
//   T & {
//     _isNew: boolean;
//     _error: E;
//   }
// >;

// export type InputDataGridProps<T extends ResultWithId, E> = {
//   formKey: string;
//   // items?: TableRow<T, E>[];
//   columns: GridColDef[];
//   _rowModesModel: GridRowModesModel;
//   validation: () => E;
// };

// export class ProcessRowUpdateError<T, E> extends Error {
//   public readonly row: T;
//   public readonly errors: E | undefined;
//   constructor(row: T, message?: string, errors?: E) {
//     super(message);
//     this.row = row;
//     this.errors = errors;

//     Object.setPrototypeOf(this, ProcessRowUpdateError.prototype);
//   }
// }

// function useInputDataGrid<T extends ResultWithId, E>({
//   formKey = "testing",
//   // items,
//   columns,
//   _rowModesModel,
//   validation,
// }: InputDataGridProps<T, E>): {
//   DataGrid: React.FC;
//   rowModesModel: GridRowModesModel;
//   setRowModesModel: Dispatch<SetStateAction<GridRowModesModel>>;
// } {
//   const {
//     t,
//     // i18n: { language },
//   } = useTranslation();
//   const { setValue, getValues } = useFormContext();
//   const [rowModesModel, setRowModesModel] =
//     useState<GridRowModesModel>(_rowModesModel);
//   const apiRef = useGridApiRef();
//   const getRowId = useCallback<GridRowIdGetter<TableRow<T, E>>>(
//     (row) => row.id!!.toString(),
//     []
//   );
//   const list: TableRow<T, E>[] = getValues(formKey);
//   const [rows, setRows] = useState<TableRow<T, E>[]>(() => {
//     const list: TableRow<T, E>[] = getValues(formKey);
//     return list && list.length > 0 ? list : [];
//   });
//   const originalRows = list && list.length > 0 ? list : [];

//   const handleSave = useCallback(
//     (id: GridRowId) => () => {
//       setRowModesModel((prevRowModesModel) => ({
//         ...prevRowModesModel,
//         [id]: { mode: GridRowModes.View },
//       }));
//     },
//     [setRowModesModel]
//   );
//   const onProcessRowUpdateError = useCallback(
//     (updateError: ProcessRowUpdateError<T, E>) => {
//       const errors = updateError.errors;
//       const row = updateError.row;
//       console.log(errors);
//       apiRef.current.updateRows([{ ...row, _error: errors }]);
//     },
//     [apiRef, rowModesModel]
//   );

//   const processRowUpdate = useCallback(
//     (
//       newRow: GridRowModel<TableRow<T, E>>,
//       originalRow: GridRowModel<TableRow<T, E>>
//     ) => {
//       /////////////////
//       // validation here
//       // const errors = validation(); //repace true with validation method
//       // if (errors) {
//       //   throw new ProcessRowUpdateError(
//       //     originalRow,
//       //     "validation error",
//       //     errors,
//       //   );
//       // }
//       /////////////////
//       const { _isNew, _error, ...updatedRow } = newRow;
//       const rowToSave = {
//         ...updatedRow,
//       } as TableRow<T, E>; /// test
//       setRows((rw) =>
//         rw.map((r) => (getRowId(r) === getRowId(originalRow) ? rowToSave : r))
//       );

//       return rowToSave;
//     },
//     [rows]
//   );

//   const addRow = useCallback(() => {
//     const newEntry = { id: Date.now(), _isNew: true } as TableRow<T, E>;
//     setRows((prev) => [...prev, newEntry]);
//     setRowModesModel((model) => ({
//       ...model,
//       [getRowId(newEntry)]: {
//         mode: GridRowModes.Edit,
//         // fieldToFocus: "team", /// test
//       },
//     }));
//   }, [getRowId]);

//   const handleCancel = useCallback(
//     (id: GridRowId) => () => {
//       setRowModesModel((model) => ({
//         ...model,
//         [id]: { mode: GridRowModes.View, ignoreModifications: true },
//       }));
//       const editedRow = rows.find((row) => getRowId(row) === id);
//       console.log(editedRow);
//       if (editedRow?._isNew) {
//         setRows((rw) => rw.filter((r) => r.id !== id));
//       } else {
//         setRows((rw) =>
//           rw.map((r) => (getRowId(r) === id ? { ...r, _error: undefined } : r))
//         );
//       }
//     },
//     [setRowModesModel, rows]
//   );

//   const handleDelete = useCallback(
//     (id: GridRowId) => () => {
//       setRows((prevRows) => prevRows.filter((row) => getRowId(row) !== id));
//     },
//     []
//   );

//   const _columns = useMemo<GridColDef[]>(
//     () => [
//       ...columns,
//       {
//         field: "actions",
//         type: "actions",
//         headerName: "edit",
//         width: 100,
//         cellClassName: "actions",
//         getActions: ({ id }: { id: GridRowId }) => {
//           const isInEditMode = rowModesModel[id]?.mode === GridRowModes.Edit;
//           if (isInEditMode) {
//             return [
//               <GridActionsCellItem
//                 icon={<SaveIcon />}
//                 label="Save"
//                 key="edit"
//                 sx={{
//                   color: "primary.main",
//                 }}
//                 onClick={handleSave(id)}
//               />,
//               <GridActionsCellItem
//                 icon={<CancelIcon />}
//                 label="Cancel"
//                 key="edit"
//                 onClick={handleCancel(id)}
//               />,
//             ];
//           }
//           return [
//             <GridActionsCellItem
//               icon={<DeleteIcon />}
//               label="Delete"
//               sx={{
//                 color: "error.main",
//               }}
//               onClick={handleDelete(id)}
//               color="inherit"
//               key="edit"
//             />,
//           ];
//         },
//       },
//     ],
//     []
//   );

//   // sync useForm
//   useEffect(() => {
//     setValue(formKey, rows);
//   }, [rows]);

//   const footer = (
//     <Box display="flex" gap={2} alignItems="center">
//       <Button
//         disableRipple
//         variant="outlined"
//         startIcon={<Add />}
//         onClick={addRow}
//         size="small"
//       >
//         {t("Add Record")}
//       </Button>
//     </Box>
//   );
//   const DataGrid: React.FC = ({ ...props }) => (
//     <StyledDataGrid
//       getRowId={getRowId as GridRowIdGetter<GridValidRowModel>}
//       apiRef={apiRef}
//       rows={rows}
//       columns={_columns}
//       editMode="row"
//       autoHeight
//       sx={{
//         "--DataGrid-overlayHeight": "100px",
//         ".MuiDataGrid-row .MuiDataGrid-cell.hasError": {
//           border: "1px solid",
//           borderColor: "error.main",
//         },
//         ".MuiDataGrid-row .MuiDataGrid-cell.hasWarning": {
//           border: "1px solid",
//           borderColor: "warning.main",
//         },
//       }}
//       disableColumnMenu
//       rowModesModel={rowModesModel}
//       onRowModesModelChange={setRowModesModel}
//       processRowUpdate={processRowUpdate as any}
//       onProcessRowUpdateError={onProcessRowUpdateError}
//       getCellClassName={(params: GridCellParams<TableRow<T, E>>) => {
//         let classname = "";
//         if (params.row._error) {
//           classname = "hasError";
//         }
//         return classname;
//       }}
//       slots={{
//         footer: FooterToolbar,
//         noRowsOverlay: NoRowsOverlay,
//       }}
//       slotProps={{
//         footer: { child: footer },
//       }}
//     />
//   );
//   return {
//     DataGrid,
//     rowModesModel,
//     setRowModesModel,
//   };
// }
// const FooterToolbar: React.FC<FooterPropsOverrides> = ({ child }) => {
//   return <GridToolbarContainer sx={{ p: 2 }}>{child}</GridToolbarContainer>;
// };
// const NoRowsOverlay: React.FC = () => {
//   const { t } = useTranslation("home");
//   return (
//     <Box
//       display="flex"
//       justifyContent="center"
//       alignItems="center"
//       height="100%"
//     >
//       <Typography variant="caption">{t("Add some entries!")}</Typography>
//     </Box>
//   );
// };
// export default useInputDataGrid;
