// redux/slices/firmwareUpdateSlice.ts
import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
import firmwareUpdate from "@/components/main/kabelueberwachung/kue705FO/handlers/firmwareUpdate";

interface FirmwareUpdateState {
  isUpdating: boolean;
  progress: number;
  status: "idle" | "loading" | "success" | "error";
  message: string;
}

const initialState: FirmwareUpdateState = {
  isUpdating: false,
  progress: 0,
  status: "idle",
  message: "",
};

export const startFirmwareUpdateThunk = createAsyncThunk(
  "firmware/update",
  async (slot: number, { dispatch, rejectWithValue }) => {
    try {
      const totalDuration = 5000;
      const intervalMs = 50;
      const steps = totalDuration / intervalMs;
      let currentStep = 0;

      dispatch(setUpdating(true));

      const interval = setInterval(() => {
        currentStep++;
        const newProgress = Math.min((currentStep / steps) * 100, 100);
        dispatch(setProgress(newProgress));
        if (currentStep >= steps) clearInterval(interval);
      }, intervalMs);

      const response = await firmwareUpdate(slot);

      if (response.message.includes("erfolgreich")) {
        return response.message;
      } else {
        return rejectWithValue("Update fehlgeschlagen");
      }
    } catch (err) {
      console.error("Fehler beim Firmwareupdate:", err);
      return rejectWithValue("Fehler beim Firmwareupdate");
    }
  }
);

const firmwareUpdateSlice = createSlice({
  name: "firmwareUpdate",
  initialState,
  reducers: {
    setUpdating: (state, action: PayloadAction<boolean>) => {
      state.isUpdating = action.payload;
    },
    setProgress: (state, action: PayloadAction<number>) => {
      state.progress = action.payload;
    },
    resetFirmwareState: () => initialState,
  },
  extraReducers: (builder) => {
    builder
      .addCase(startFirmwareUpdateThunk.pending, (state) => {
        state.status = "loading";
        state.message = "Update gestartet";
      })
      .addCase(startFirmwareUpdateThunk.fulfilled, (state, action) => {
        state.status = "success";
        state.message = action.payload;
        state.isUpdating = false;
        state.progress = 100;
      })
      .addCase(startFirmwareUpdateThunk.rejected, (state, action) => {
        state.status = "error";
        state.message = action.payload as string;
        state.isUpdating = false;
        state.progress = 100;
      });
  },
});

export const { setUpdating, setProgress, resetFirmwareState } =
  firmwareUpdateSlice.actions;
export default firmwareUpdateSlice.reducer;
