import type { CropPageState } from "./types";

export type CropPageAction =
  | { type: "SET_ROWS"; payload: CropPageState["rows"] }
  | { type: "SET_FORM_FIELD"; payload: { key: keyof CropPageState["form"]; value: string } }
  | { type: "RESET_FORM" }
  | { type: "SET_LOADING"; payload: boolean }
  | { type: "SET_SUBMITTING"; payload: boolean }
  | { type: "SET_ERROR"; payload: string | null };

export function cropReducer(state: CropPageState, action: CropPageAction): CropPageState {
  switch (action.type) {
    case "SET_ROWS":
      return { ...state, rows: action.payload };
    case "SET_FORM_FIELD":
      return { ...state, form: { ...state.form, [action.payload.key]: action.payload.value } };
    case "RESET_FORM":
      return { ...state, form: { cropName: "" } };
    case "SET_LOADING":
      return { ...state, loading: action.payload };
    case "SET_SUBMITTING":
      return { ...state, submitting: action.payload };
    case "SET_ERROR":
      return { ...state, error: action.payload };
    default:
      return state;
  }
}
