import {
  CreateCorrectiveActionPayload,
  CreateIncidentInjuryPayload,
  CreateIncidentPayload,
  CreateIncidentWitnessPayload,
  CreateRegulatoryReportPayload,
  DeleteIncidentDocumentPayload,
  DeleteIncidentInjuryPayload,
  DeleteIncidentWitnessPayload,
  Incident,
  IncidentCorrectiveAction,
  IncidentDocument,
  IncidentInjury,
  IncidentRegulatoryReport,
  IncidentStats,
  IncidentTimeline,
  IncidentWitness,
  UpdateCorrectiveActionPayload,
  UpdateIncidentInjuryPayload,
  UpdateIncidentPayload,
  UpdateIncidentStatusPayload,
  UpdateIncidentWitnessPayload,
  UpdateRegulatoryReportPayload,
  UploadIncidentDocumentPayload,
} from '@/interface/Incident';
import { RejectedActionPayload, ServerErrorResponse } from '@/interface/Shared';
import { apiDelete, apiGet, apiPost, apiPut } from '@/services/api/api';
import Helpers from '@/utilities/Helpers';
import { createAsyncThunk, createSlice, Draft, PayloadAction } from '@reduxjs/toolkit';
import { message } from 'antd';
import axios, { AxiosResponse } from 'axios';
import { IncidentActions } from './actionTypes';

interface IncidentState {
  incidents: Incident[];
  incident: Incident | null;
  injuries: IncidentInjury[];
  documents: IncidentDocument[];
  witnesses: IncidentWitness[];
  correctiveActions: IncidentCorrectiveAction[];
  regulatoryReports: IncidentRegulatoryReport[];
  timeline: IncidentTimeline[];
  stats: IncidentStats | null;
  loading: boolean;
  subLoading: boolean;
  error: string | null;
}

const initialState: IncidentState = {
  incidents: [],
  incident: null,
  injuries: [],
  documents: [],
  witnesses: [],
  correctiveActions: [],
  regulatoryReports: [],
  timeline: [],
  stats: null,
  loading: false,
  subLoading: false,
  error: null,
};

export const fetchIncidents = createAsyncThunk(
  IncidentActions.FETCH_INCIDENTS,
  async (queryString: string | undefined, { rejectWithValue }) => {
    try {
      const query = queryString ? `?${queryString}` : '';
      const response = (await apiGet(`/incidents${query}`)) as AxiosResponse<Incident[]>;
      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const fetchIncident = createAsyncThunk(
  IncidentActions.FETCH_INCIDENT,
  async (id: string, { rejectWithValue }) => {
    try {
      const response = (await apiGet(`/incidents/${id}`)) as AxiosResponse<Incident>;
      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const createIncident = createAsyncThunk(
  IncidentActions.CREATE_INCIDENT,
  async (payload: CreateIncidentPayload, { rejectWithValue }) => {
    try {
      const response = (await apiPost('/incidents', payload)) as AxiosResponse<Incident>;
      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const updateIncident = createAsyncThunk(
  IncidentActions.UPDATE_INCIDENT,
  async (payload: UpdateIncidentPayload, { rejectWithValue }) => {
    try {
      const { id, ...rest } = payload;
      const response = (await apiPut(`/incidents/${id}`, rest)) as AxiosResponse<Incident>;
      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const updateIncidentStatus = createAsyncThunk(
  IncidentActions.UPDATE_INCIDENT_STATUS,
  async (payload: UpdateIncidentStatusPayload, { rejectWithValue }) => {
    try {
      const { id, ...rest } = payload;
      const response = (await apiPut(`/incidents/${id}/status`, rest)) as AxiosResponse<Incident>;
      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const fetchIncidentInjuries = createAsyncThunk(
  IncidentActions.FETCH_INCIDENT_INJURIES,
  async (incidentId: string, { rejectWithValue }) => {
    try {
      const response = (await apiGet(`/incidents/${incidentId}/injuries`)) as AxiosResponse<
        IncidentInjury[]
      >;
      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const createIncidentInjury = createAsyncThunk(
  IncidentActions.CREATE_INCIDENT_INJURY,
  async (payload: CreateIncidentInjuryPayload, { rejectWithValue }) => {
    try {
      const { incident_id, ...rest } = payload;
      const response = (await apiPost(
        `/incidents/${incident_id}/injuries`,
        rest,
      )) as AxiosResponse<IncidentInjury>;
      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const updateIncidentInjury = createAsyncThunk(
  IncidentActions.UPDATE_INCIDENT_INJURY,
  async (payload: UpdateIncidentInjuryPayload, { rejectWithValue }) => {
    try {
      const { incident_id, injury_id, ...rest } = payload;
      const response = (await apiPut(
        `/incidents/${incident_id}/injuries/${injury_id}`,
        rest,
      )) as AxiosResponse<IncidentInjury>;
      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const deleteIncidentInjury = createAsyncThunk(
  IncidentActions.DELETE_INCIDENT_INJURY,
  async (payload: DeleteIncidentInjuryPayload, { rejectWithValue }) => {
    try {
      const response = (await apiDelete(
        `/incidents/${payload.incident_id}/injuries/${payload.injury_id}`,
      )) as AxiosResponse<{ message: string }>;
      return { ...payload, message: response.data.message };
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const fetchIncidentDocuments = createAsyncThunk(
  IncidentActions.FETCH_INCIDENT_DOCUMENTS,
  async (incidentId: string, { rejectWithValue }) => {
    try {
      const response = (await apiGet(`/incidents/${incidentId}/documents`)) as AxiosResponse<
        IncidentDocument[]
      >;
      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const uploadIncidentDocument = createAsyncThunk(
  IncidentActions.UPLOAD_INCIDENT_DOCUMENT,
  async (payload: UploadIncidentDocumentPayload, { rejectWithValue }) => {
    try {
      const formData = new FormData();
      formData.append('document_type', payload.document_type);
      formData.append('file', payload.file);

      const response = (await apiPost(`/incidents/${payload.incident_id}/documents`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      })) as AxiosResponse<IncidentDocument>;

      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const deleteIncidentDocument = createAsyncThunk(
  IncidentActions.DELETE_INCIDENT_DOCUMENT,
  async (payload: DeleteIncidentDocumentPayload, { rejectWithValue }) => {
    try {
      const response = (await apiDelete(
        `/incidents/${payload.incident_id}/documents/${payload.document_id}`,
      )) as AxiosResponse<{ message: string }>;
      return { ...payload, message: response.data.message };
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const fetchIncidentWitnesses = createAsyncThunk(
  IncidentActions.FETCH_INCIDENT_WITNESSES,
  async (incidentId: string, { rejectWithValue }) => {
    try {
      const response = (await apiGet(`/incidents/${incidentId}/witnesses`)) as AxiosResponse<
        IncidentWitness[]
      >;
      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const createIncidentWitness = createAsyncThunk(
  IncidentActions.CREATE_INCIDENT_WITNESS,
  async (payload: CreateIncidentWitnessPayload, { rejectWithValue }) => {
    try {
      const { incident_id, ...rest } = payload;
      const response = (await apiPost(
        `/incidents/${incident_id}/witnesses`,
        rest,
      )) as AxiosResponse<IncidentWitness>;
      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const updateIncidentWitness = createAsyncThunk(
  IncidentActions.UPDATE_INCIDENT_WITNESS,
  async (payload: UpdateIncidentWitnessPayload, { rejectWithValue }) => {
    try {
      const { incident_id, witness_id, ...rest } = payload;
      const response = (await apiPut(
        `/incidents/${incident_id}/witnesses/${witness_id}`,
        rest,
      )) as AxiosResponse<IncidentWitness>;
      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const deleteIncidentWitness = createAsyncThunk(
  IncidentActions.DELETE_INCIDENT_WITNESS,
  async (payload: DeleteIncidentWitnessPayload, { rejectWithValue }) => {
    try {
      const response = (await apiDelete(
        `/incidents/${payload.incident_id}/witnesses/${payload.witness_id}`,
      )) as AxiosResponse<{ message: string }>;
      return { ...payload, message: response.data.message };
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const fetchCorrectiveActions = createAsyncThunk(
  IncidentActions.FETCH_CORRECTIVE_ACTIONS,
  async (incidentId: string, { rejectWithValue }) => {
    try {
      const response = (await apiGet(
        `/incidents/${incidentId}/corrective-actions`,
      )) as AxiosResponse<IncidentCorrectiveAction[]>;
      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const createCorrectiveAction = createAsyncThunk(
  IncidentActions.CREATE_CORRECTIVE_ACTION,
  async (payload: CreateCorrectiveActionPayload, { rejectWithValue }) => {
    try {
      const { incident_id, ...rest } = payload;
      const response = (await apiPost(
        `/incidents/${incident_id}/corrective-actions`,
        rest,
      )) as AxiosResponse<IncidentCorrectiveAction>;
      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const updateCorrectiveAction = createAsyncThunk(
  IncidentActions.UPDATE_CORRECTIVE_ACTION,
  async (payload: UpdateCorrectiveActionPayload, { rejectWithValue }) => {
    try {
      const { incident_id, corrective_action_id, ...rest } = payload;
      const response = (await apiPut(
        `/incidents/${incident_id}/corrective-actions/${corrective_action_id}`,
        rest,
      )) as AxiosResponse<IncidentCorrectiveAction>;
      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const fetchRegulatoryReports = createAsyncThunk(
  IncidentActions.FETCH_REGULATORY_REPORTS,
  async (incidentId: string, { rejectWithValue }) => {
    try {
      const response = (await apiGet(
        `/incidents/${incidentId}/regulatory-reports`,
      )) as AxiosResponse<IncidentRegulatoryReport[]>;
      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const createRegulatoryReport = createAsyncThunk(
  IncidentActions.CREATE_REGULATORY_REPORT,
  async (payload: CreateRegulatoryReportPayload, { rejectWithValue }) => {
    try {
      const { incident_id, ...rest } = payload;
      const response = (await apiPost(
        `/incidents/${incident_id}/regulatory-reports`,
        rest,
      )) as AxiosResponse<IncidentRegulatoryReport>;
      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const updateRegulatoryReport = createAsyncThunk(
  IncidentActions.UPDATE_REGULATORY_REPORT,
  async (payload: UpdateRegulatoryReportPayload, { rejectWithValue }) => {
    try {
      const { incident_id, report_id, ...rest } = payload;
      const response = (await apiPut(
        `/incidents/${incident_id}/regulatory-reports/${report_id}`,
        rest,
      )) as AxiosResponse<IncidentRegulatoryReport>;
      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const fetchIncidentTimeline = createAsyncThunk(
  IncidentActions.FETCH_INCIDENT_TIMELINE,
  async (incidentId: string, { rejectWithValue }) => {
    try {
      const response = (await apiGet(`/incidents/${incidentId}/timeline`)) as AxiosResponse<
        IncidentTimeline[]
      >;
      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const fetchIncidentStats = createAsyncThunk(
  IncidentActions.FETCH_INCIDENT_STATS,
  async (_, { rejectWithValue }) => {
    try {
      const response = (await apiGet('/incidents/stats')) as AxiosResponse<IncidentStats>;
      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

const IncidentSlice = createSlice({
  name: 'incidents',
  initialState,
  reducers: {
    clearIncidentState: (state: Draft<IncidentState>) => {
      state.incident = null;
      state.injuries = [];
      state.documents = [];
      state.witnesses = [];
      state.correctiveActions = [];
      state.regulatoryReports = [];
      state.timeline = [];
    },
  },
  extraReducers(builder) {
    builder
      .addCase(fetchIncidents.pending, (state: Draft<IncidentState>) => {
        state.loading = true;
      })
      .addCase(
        fetchIncidents.fulfilled,
        (state: Draft<IncidentState>, action: PayloadAction<Incident[]>) => {
          state.loading = false;
          state.incidents = action.payload;
        },
      )
      .addCase(
        fetchIncidents.rejected,
        (state: Draft<IncidentState>, action: RejectedActionPayload) => {
          state.loading = false;
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(fetchIncident.pending, (state: Draft<IncidentState>) => {
        state.loading = true;
      })
      .addCase(
        fetchIncident.fulfilled,
        (state: Draft<IncidentState>, action: PayloadAction<Incident>) => {
          state.loading = false;
          state.incident = action.payload;
        },
      )
      .addCase(
        fetchIncident.rejected,
        (state: Draft<IncidentState>, action: RejectedActionPayload) => {
          state.loading = false;
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(createIncident.pending, (state: Draft<IncidentState>) => {
        state.loading = true;
      })
      .addCase(
        createIncident.fulfilled,
        (state: Draft<IncidentState>, action: PayloadAction<Incident>) => {
          state.loading = false;
          state.incident = action.payload;
          state.incidents.unshift(action.payload);
          message.success('Incident reported successfully', 8);
        },
      )
      .addCase(
        createIncident.rejected,
        (state: Draft<IncidentState>, action: RejectedActionPayload) => {
          state.loading = false;
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(updateIncident.pending, (state: Draft<IncidentState>) => {
        state.loading = true;
      })
      .addCase(
        updateIncident.fulfilled,
        (state: Draft<IncidentState>, action: PayloadAction<Incident>) => {
          state.loading = false;
          state.incident = action.payload;
          state.incidents = state.incidents.map((item) =>
            item.id === action.payload.id ? action.payload : item,
          );
          message.success('Incident updated successfully', 8);
        },
      )
      .addCase(
        updateIncident.rejected,
        (state: Draft<IncidentState>, action: RejectedActionPayload) => {
          state.loading = false;
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(updateIncidentStatus.pending, (state: Draft<IncidentState>) => {
        state.loading = true;
      })
      .addCase(
        updateIncidentStatus.fulfilled,
        (state: Draft<IncidentState>, action: PayloadAction<Incident>) => {
          state.loading = false;
          state.incident = action.payload;
          state.incidents = state.incidents.map((item) =>
            item.id === action.payload.id ? action.payload : item,
          );
          message.success('Incident status updated successfully', 8);
        },
      )
      .addCase(
        updateIncidentStatus.rejected,
        (state: Draft<IncidentState>, action: RejectedActionPayload) => {
          state.loading = false;
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(fetchIncidentInjuries.pending, (state: Draft<IncidentState>) => {
        state.subLoading = true;
      })
      .addCase(
        fetchIncidentInjuries.fulfilled,
        (state: Draft<IncidentState>, action: PayloadAction<IncidentInjury[]>) => {
          state.subLoading = false;
          state.injuries = action.payload;
        },
      )
      .addCase(
        fetchIncidentInjuries.rejected,
        (state: Draft<IncidentState>, action: RejectedActionPayload) => {
          state.subLoading = false;
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(
        createIncidentInjury.fulfilled,
        (state: Draft<IncidentState>, action: PayloadAction<IncidentInjury>) => {
          state.injuries.unshift(action.payload);
          message.success('Injury record added successfully', 8);
        },
      )
      .addCase(
        createIncidentInjury.rejected,
        (state: Draft<IncidentState>, action: RejectedActionPayload) => {
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(
        updateIncidentInjury.fulfilled,
        (state: Draft<IncidentState>, action: PayloadAction<IncidentInjury>) => {
          state.injuries = state.injuries.map((item) =>
            item.id === action.payload.id ? action.payload : item,
          );
          message.success('Injury record updated successfully', 8);
        },
      )
      .addCase(
        updateIncidentInjury.rejected,
        (state: Draft<IncidentState>, action: RejectedActionPayload) => {
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(deleteIncidentInjury.fulfilled, (state: Draft<IncidentState>, action) => {
        state.injuries = state.injuries.filter((item) => item.id !== action.payload.injury_id);
        message.success(action.payload.message, 8);
      })
      .addCase(
        deleteIncidentInjury.rejected,
        (state: Draft<IncidentState>, action: RejectedActionPayload) => {
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(
        fetchIncidentDocuments.fulfilled,
        (state: Draft<IncidentState>, action: PayloadAction<IncidentDocument[]>) => {
          state.documents = action.payload;
        },
      )
      .addCase(
        fetchIncidentDocuments.rejected,
        (state: Draft<IncidentState>, action: RejectedActionPayload) => {
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(
        uploadIncidentDocument.fulfilled,
        (state: Draft<IncidentState>, action: PayloadAction<IncidentDocument>) => {
          state.documents.unshift(action.payload);
          message.success('Document uploaded successfully', 8);
        },
      )
      .addCase(
        uploadIncidentDocument.rejected,
        (state: Draft<IncidentState>, action: RejectedActionPayload) => {
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(deleteIncidentDocument.fulfilled, (state: Draft<IncidentState>, action) => {
        state.documents = state.documents.filter((item) => item.id !== action.payload.document_id);
        message.success(action.payload.message, 8);
      })
      .addCase(
        deleteIncidentDocument.rejected,
        (state: Draft<IncidentState>, action: RejectedActionPayload) => {
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(
        fetchIncidentWitnesses.fulfilled,
        (state: Draft<IncidentState>, action: PayloadAction<IncidentWitness[]>) => {
          state.witnesses = action.payload;
        },
      )
      .addCase(
        fetchIncidentWitnesses.rejected,
        (state: Draft<IncidentState>, action: RejectedActionPayload) => {
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(
        createIncidentWitness.fulfilled,
        (state: Draft<IncidentState>, action: PayloadAction<IncidentWitness>) => {
          state.witnesses.unshift(action.payload);
          message.success('Witness added successfully', 8);
        },
      )
      .addCase(
        createIncidentWitness.rejected,
        (state: Draft<IncidentState>, action: RejectedActionPayload) => {
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(
        updateIncidentWitness.fulfilled,
        (state: Draft<IncidentState>, action: PayloadAction<IncidentWitness>) => {
          state.witnesses = state.witnesses.map((item) =>
            item.id === action.payload.id ? action.payload : item,
          );
          message.success('Witness updated successfully', 8);
        },
      )
      .addCase(
        updateIncidentWitness.rejected,
        (state: Draft<IncidentState>, action: RejectedActionPayload) => {
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(
        deleteIncidentWitness.fulfilled,
        (state: Draft<IncidentState>, action) => {
          state.witnesses = state.witnesses.filter((item) => item.id !== action.payload.witness_id);
          message.success(action.payload.message, 8);
        },
      )
      .addCase(
        deleteIncidentWitness.rejected,
        (state: Draft<IncidentState>, action: RejectedActionPayload) => {
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(
        fetchCorrectiveActions.fulfilled,
        (state: Draft<IncidentState>, action: PayloadAction<IncidentCorrectiveAction[]>) => {
          state.correctiveActions = action.payload;
        },
      )
      .addCase(
        fetchCorrectiveActions.rejected,
        (state: Draft<IncidentState>, action: RejectedActionPayload) => {
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(
        createCorrectiveAction.fulfilled,
        (state: Draft<IncidentState>, action: PayloadAction<IncidentCorrectiveAction>) => {
          state.correctiveActions.unshift(action.payload);
          message.success('Corrective action added successfully', 8);
        },
      )
      .addCase(
        createCorrectiveAction.rejected,
        (state: Draft<IncidentState>, action: RejectedActionPayload) => {
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(
        updateCorrectiveAction.fulfilled,
        (state: Draft<IncidentState>, action: PayloadAction<IncidentCorrectiveAction>) => {
          state.correctiveActions = state.correctiveActions.map((item) =>
            item.id === action.payload.id ? action.payload : item,
          );
          message.success('Corrective action updated successfully', 8);
        },
      )
      .addCase(
        updateCorrectiveAction.rejected,
        (state: Draft<IncidentState>, action: RejectedActionPayload) => {
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(
        fetchRegulatoryReports.fulfilled,
        (state: Draft<IncidentState>, action: PayloadAction<IncidentRegulatoryReport[]>) => {
          state.regulatoryReports = action.payload;
        },
      )
      .addCase(
        fetchRegulatoryReports.rejected,
        (state: Draft<IncidentState>, action: RejectedActionPayload) => {
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(
        createRegulatoryReport.fulfilled,
        (state: Draft<IncidentState>, action: PayloadAction<IncidentRegulatoryReport>) => {
          state.regulatoryReports.unshift(action.payload);
          message.success('Regulatory report added successfully', 8);
        },
      )
      .addCase(
        createRegulatoryReport.rejected,
        (state: Draft<IncidentState>, action: RejectedActionPayload) => {
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(
        updateRegulatoryReport.fulfilled,
        (state: Draft<IncidentState>, action: PayloadAction<IncidentRegulatoryReport>) => {
          state.regulatoryReports = state.regulatoryReports.map((item) =>
            item.id === action.payload.id ? action.payload : item,
          );
          message.success('Regulatory report updated successfully', 8);
        },
      )
      .addCase(
        updateRegulatoryReport.rejected,
        (state: Draft<IncidentState>, action: RejectedActionPayload) => {
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(
        fetchIncidentTimeline.fulfilled,
        (state: Draft<IncidentState>, action: PayloadAction<IncidentTimeline[]>) => {
          state.timeline = action.payload;
        },
      )
      .addCase(
        fetchIncidentTimeline.rejected,
        (state: Draft<IncidentState>, action: RejectedActionPayload) => {
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(
        fetchIncidentStats.fulfilled,
        (state: Draft<IncidentState>, action: PayloadAction<IncidentStats>) => {
          state.stats = action.payload;
        },
      )
      .addCase(
        fetchIncidentStats.rejected,
        (state: Draft<IncidentState>, action: RejectedActionPayload) => {
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );
  },
});

export const { clearIncidentState } = IncidentSlice.actions;
export default IncidentSlice;
export type { IncidentState };
