// reducers/incidentReportReducer.ts
import { Toast } from 'native-base';
import { REHYDRATE } from 'redux-persist';
import {
    GET_INCIDENT_REPORT_DASHBOARD_FORM_FAILED,
    GET_INCIDENT_REPORT_DASHBOARD_FORM_REQUEST,
    GET_INCIDENT_REPORT_DASHBOARD_FORM_SUCCESS,
    SUBMIT_INCIDENT_FAILED,
    SUBMIT_INCIDENT_REQUEST,
    SUBMIT_INCIDENT_SUCCESS,
} from '../actions/types';

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

// =======================
// Action Types
// =======================
type IncidentReportAction =
  | { type: typeof REHYDRATE; payload?: { incidentReport?: IncidentReportState } }
  | { type: typeof SUBMIT_INCIDENT_REQUEST }
  | { type: typeof SUBMIT_INCIDENT_SUCCESS }
  | { type: typeof SUBMIT_INCIDENT_FAILED; payload?: Record<string, any> }
  | { type: typeof GET_INCIDENT_REPORT_DASHBOARD_FORM_REQUEST }
  | { type: typeof GET_INCIDENT_REPORT_DASHBOARD_FORM_SUCCESS; payload: Record<string, any> }
  | { type: typeof GET_INCIDENT_REPORT_DASHBOARD_FORM_FAILED; payload?: Record<string, any> };

// =======================
// Initial State
// =======================
const initialState: IncidentReportState = {
  incidentReportDashboardForm: {},
  loading: false,
  error: {},
};

// =======================
// Reducer
// =======================
export default function incidentReport(
  state: IncidentReportState = initialState,
  action: IncidentReportAction
): IncidentReportState {
  switch (action.type) {
    case REHYDRATE:
      return action.payload?.incidentReport ?? state;

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

    case SUBMIT_INCIDENT_SUCCESS:
      Toast.show({
        title: 'Incident Submitted',
        description: 'Incident submitted successfully!',
        placement: 'top',
        duration: 4000,
        variant: 'solid',
        backgroundColor: 'green.500',
      });
      return { ...state, loading: false, error: {} };

    case SUBMIT_INCIDENT_FAILED:
      Toast.show({
        title: 'Submission Failed',
        description: 'Something went wrong while submitting incident.',
        placement: 'top',
        duration: 4000,
        variant: 'solid',
        backgroundColor: 'red.500',
      });
      return { ...state, loading: false, error: action.payload ?? {} };

    case GET_INCIDENT_REPORT_DASHBOARD_FORM_SUCCESS:
      return { ...state, incidentReportDashboardForm: action.payload ?? {}, loading: false, error: {} };

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

    default:
      return state;
  }
}
