import { emptyPersonForm, type PersonPageState } from "./types";

export type PersonPageAction =
  | { type: "SET_ROWS"; payload: PersonPageState["rows"] }
  | { type: "SET_FORM_FIELD"; payload: { key: keyof PersonPageState["form"]; value: string } }
  | { type: "SET_FORM"; payload: Partial<PersonPageState["form"]> }
  | { type: "RESET_FORM" }
  | { type: "SET_LOADING"; payload: boolean }
  | { type: "SET_SUBMITTING"; payload: boolean }
  | { type: "SET_ERROR"; payload: string | null };

export function personReducer(state: PersonPageState, action: PersonPageAction): PersonPageState {
  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 "SET_FORM":
      return { ...state, form: { ...state.form, ...action.payload } };
    case "RESET_FORM":
      return { ...state, form: emptyPersonForm };
    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;
  }
}
