import { PayloadAction, createSlice } from "@reduxjs/toolkit";
import { Typist } from "api";
import { TypistGroupState } from "./state";
import { listTypistGroupsAsync, listTypistsAsync } from "./operations";

const initialState: TypistGroupState = {
  apps: {
    isLoading: false,
    selectedTypists: [],
    groupName: "",
  },
  domain: {
    typistGroups: [],
    typists: [],
  },
};

export const typistGroupSlice = createSlice({
  name: "typistGroup",
  initialState,
  reducers: {
    cleanupAddCroup: (state) => {
      state.apps.groupName = "";
      state.apps.selectedTypists = [];
    },
    addSelectedTypist: (state, action: PayloadAction<{ typist: Typist }>) => {
      const { typist } = action.payload;

      const selectedTypists = [...state.apps.selectedTypists, typist];
      if (!state.apps.selectedTypists.find((x) => x.id === typist.id)) {
        state.apps.selectedTypists = selectedTypists.sort(
          (a, b) => a.id - b.id
        );
      }
    },
    removeSelectedTypist: (
      state,
      action: PayloadAction<{ typist: Typist }>
    ) => {
      const { typist } = action.payload;

      const selectedTypists = state.apps.selectedTypists.filter(
        (x) => x.id !== typist.id
      );
      state.apps.selectedTypists = selectedTypists.sort((a, b) => a.id - b.id);
    },
    changeGroupName: (state, action: PayloadAction<{ groupName: string }>) => {
      const { groupName } = action.payload;
      state.apps.groupName = groupName;
    },
  },
  extraReducers: (builder) => {
    builder.addCase(listTypistGroupsAsync.pending, (state) => {
      state.apps.isLoading = true;
    });
    builder.addCase(listTypistGroupsAsync.fulfilled, (state, action) => {
      state.domain.typistGroups = action.payload.typistGroups;
      state.apps.isLoading = false;
    });
    builder.addCase(listTypistGroupsAsync.rejected, (state) => {
      state.apps.isLoading = false;
    });
    builder.addCase(listTypistsAsync.pending, (state) => {
      state.apps.isLoading = true;
    });
    builder.addCase(listTypistsAsync.fulfilled, (state, action) => {
      state.domain.typists = action.payload.typists;
      state.apps.isLoading = false;
    });
    builder.addCase(listTypistsAsync.rejected, (state) => {
      state.apps.isLoading = false;
    });
  },
});

export const {
  cleanupAddCroup,
  addSelectedTypist,
  removeSelectedTypist,
  changeGroupName,
} = typistGroupSlice.actions;

export default typistGroupSlice.reducer;
