import { useEffect, useState } from 'react';
import { Data } from '../../../types';

export const useRowEditing = <T extends Data>(
  allowEditing: boolean,
  updateItem: (currentItem: T, newItem: T) => void,
): {
  readonly editingRow: T | undefined;
  readonly isEditing: boolean;
  readonly startEditing: (item: T) => void;
  readonly finishEditing: (item: T) => void;
} => {
  const [editingRow, setEditingRow] = useState<T>();

  useEffect(() => {
    if (!allowEditing) {
      setEditingRow(undefined);
    }
  }, [allowEditing]);

  const startEditing = (item: T): void => {
    allowEditing && setEditingRow(item);
  };

  const finishEditing = (item: T): void => {
    updateItem(editingRow as T, item);
    setEditingRow(undefined);
  };

  return {
    editingRow,
    isEditing: !!editingRow,
    startEditing,
    finishEditing,
  };
};
