// reducers/auditReducer.ts
import { Toast } from "native-base";
import { REHYDRATE } from "redux-persist";
import {
    GET_AUDIT_FORM_DATA_FAILED,
    GET_AUDIT_FORM_DATA_REQUEST,
    GET_AUDIT_FORM_DATA_SUCCESS,
    SUBMIT_AUDIT_FAILED,
    SUBMIT_AUDIT_REQUEST,
    SUBMIT_AUDIT_SUCCESS,
} from "../actions/types";

// =======================
// Types
// =======================
export interface AuditFormState {
  data: Record<string, any>;
  loading: boolean;
  error: Record<string, any>;
}

export interface AuditSubmitState {
  data: Record<string, any>;
  loading: boolean;
  error: Record<string, any>;
}

// Action types
type AuditFormAction =
  | { type: typeof REHYDRATE; payload?: { auditFormData?: AuditFormState } }
  | { type: typeof GET_AUDIT_FORM_DATA_REQUEST }
  | { type: typeof GET_AUDIT_FORM_DATA_SUCCESS; payload: Record<string, any> }
  | { type: typeof GET_AUDIT_FORM_DATA_FAILED; payload: Record<string, any> };

type AuditSubmitAction =
  | { type: typeof SUBMIT_AUDIT_REQUEST }
  | { type: typeof SUBMIT_AUDIT_SUCCESS; payload: Record<string, any> }
  | { type: typeof SUBMIT_AUDIT_FAILED; payload: Record<string, any> };

// =======================
// Initial States
// =======================
const initialAuditFormState: AuditFormState = {
  data: {},
  loading: false,
  error: {},
};

const initialAuditSubmitState: AuditSubmitState = {
  data: {},
  loading: false,
  error: {},
};

// =======================
// Reducers
// =======================
export const auditFormData = (
  state: AuditFormState = initialAuditFormState,
  action: AuditFormAction
): AuditFormState => {
  switch (action.type) {
    case REHYDRATE:
      return action.payload?.auditFormData
        ? { ...action.payload.auditFormData }
        : initialAuditFormState;

    case GET_AUDIT_FORM_DATA_REQUEST:
      return { ...state, loading: true, error: {} };

    case GET_AUDIT_FORM_DATA_SUCCESS:
      return { ...state, data: action.payload, loading: false, error: {} };

    case GET_AUDIT_FORM_DATA_FAILED:
      return { ...state, loading: false, error: action.payload };

    default:
      return state;
  }
};

export const auditSubmitData = (
  state: AuditSubmitState = initialAuditSubmitState,
  action: AuditSubmitAction
): AuditSubmitState => {
  switch (action.type) {
    case SUBMIT_AUDIT_REQUEST:
      return { ...state, loading: true, error: {} };

    case SUBMIT_AUDIT_SUCCESS:
      Toast.show({
        title: "Audit Submitted...",
        placement: "top",
        duration: 4000,
      });
      return { ...state, data: action.payload, loading: false, error: {} };

    case SUBMIT_AUDIT_FAILED:
      Toast.show({
        title: "Something went wrong while submitting audit...",
        placement: "top",
        duration: 4000,
      });
      return { ...state, loading: false, error: action.payload };

    default:
      return state;
  }
};
