/* eslint-disable import/order */
/* eslint-disable @typescript-eslint/consistent-type-imports */

import { createSlice, type PayloadAction } from "@reduxjs/toolkit";
import { devisState } from "./type";
import { changerStatutDevis, createDevis, devisToCommande, devisToFacture, getDevisById, getDevisList, selectDevisAsync, updateDevis } from "./thunk";
import { DevisListItem, DevisStatusResponse } from "@/types/devisType";
import { StatusResponse, TransformationResponse } from "@/types/sageTypes";

const initialState: devisState = {
    status: "idle",
    error: null,
    devis: [],
    devisSelected: null,
};

const devisSlice = createSlice({
  name: "devis",
  initialState,
  reducers: {
    selectDevis: (state, action: PayloadAction<DevisListItem>) => {
      state.devisSelected = action.payload;
    }
  },
  extraReducers: (builder) => {


  /**
   * get all devis
   */
    builder.addCase(getDevisList.fulfilled, (state, action) => {
      const data = action.payload.map((d: DevisListItem) => ({
        ...d,
        a_deja_ete_transforme: d.a_deja_ete_transforme ?? false,
        isVerified: d.isVerified ?? false,
      }));

      state.devis = data;
      state.error = null;
      state.status = "succeeded";
    });

    builder.addCase(getDevisList.pending, (state) => {
      state.status = "loading";
    });

    builder.addCase(getDevisList.rejected, (state, action) => {
      state.status = "failed";
      state.error = action.error.message || "An error occurred";
    });


    /**
     * get devis by id
     */
    builder.addCase(getDevisById.pending, (state) => {
      state.status = "loading";
    });

    builder.addCase(getDevisById.fulfilled, (state, action) => {
      const payload = action.payload as any;
      const data = payload.data as DevisListItem
      
      const idx = state.devis.findIndex((n) => n.numero === data.numero);

      if (idx !== -1) {
        state.devis[idx] = data;
      } else {
        state.devis.push(data);
      }

      state.status = "succeeded";
      state.error = null;
    });

    builder.addCase(getDevisById.rejected, (state, action) => {
      state.status = "failed";
      state.error = (action.payload as string) || action.error.message || "An error occurred";
    });


  /**
   * verified status devis
   */
    builder.addCase(selectDevisAsync.fulfilled, (state, action) => {
      state.devisSelected = {
        ...action.payload,
        isVerified: true 
      };
      const idx = state.devis.findIndex(d => d.numero === action.payload.numero);
      if (idx !== -1) {
        state.devis[idx] = state.devisSelected;
      } else {
        state.devis.push(state.devisSelected);
      }
    });


  /**
   * create devis
   */
    builder.addCase(createDevis.pending, (state) => {
      state.status = "loading";
    });

    builder.addCase(createDevis.fulfilled, (state) => {
      state.status = "succeeded";
      state.error = null;
    });

    builder.addCase(createDevis.rejected, (state, action) => {
      state.status = "failed";
      state.error = (action.payload as string) || action.error.message || "An error occurred";
    });

  /**
    * update devis
    */
    builder.addCase(updateDevis.pending, (state) => {
      state.status = "loading";
    });

    builder.addCase(updateDevis.fulfilled, (state) => {
      state.status = "succeeded";
      state.error = null;
    });

    builder.addCase(updateDevis.rejected, (state, action) => {
      state.status = "failed";
      state.error = (action.payload as string) || action.error.message || "An error occurred";
    });



    /**
     * update devis status
     */
    builder.addCase(changerStatutDevis.pending, (state) => {
      state.status = "loading";
    });

    builder.addCase(changerStatutDevis.fulfilled, (state, action) => {
      const data = action.payload as StatusResponse;

      const idx = state.devis.findIndex((n) => n.numero === data.document_id);
      
      if (idx !== -1) {
        const oldItem = state.devis[idx];

        state.devis[idx] = {
          ...oldItem,
          statut: data.statut_nouveau
        };
      }

      if (state.devisSelected?.numero === data.document_id) {
        const oldItem = state.devisSelected;

        state.devisSelected= {
          ...oldItem,
          statut: data.statut_nouveau

        };
      }

      state.status = "succeeded";
      state.error = null;
    });

    builder.addCase(changerStatutDevis.rejected, (state, action) => {
      state.status = "failed";
      state.error = (action.payload as string) || action.error.message || "An error occurred";
    });



    /**
     * devis to commande
     */
    builder.addCase(devisToCommande.pending, (state) => {
      state.status = "loading";
    });

    builder.addCase(devisToCommande.fulfilled, (state, action) => {
      const data = action.payload as TransformationResponse;
      const idx = state.devis.findIndex((n) => n.numero === data.document_source);
      if (idx !== -1) {
        state.devis.splice(idx, 1)
      }

      state.status = "succeeded";
      state.error = null;
    });

    builder.addCase(devisToCommande.rejected, (state, action) => {
      state.status = "failed";
      state.error = (action.payload as string) || action.error.message || "An error occurred";
    });


    /**
     * devis to facture
     */
    builder.addCase(devisToFacture.pending, (state) => {
      state.status = "loading";
    });

    builder.addCase(devisToFacture.fulfilled, (state, action) => {
      const data = action.payload as TransformationResponse;
      const idx = state.devis.findIndex((n) => n.numero === data.document_source);
      if (idx !== -1) {
        state.devis.splice(idx, 1)
      }

      state.status = "succeeded";
      state.error = null;
    });

    builder.addCase(devisToFacture.rejected, (state, action) => {
      state.status = "failed";
      state.error = (action.payload as string) || action.error.message || "An error occurred";
    });
  },
});


export const { selectDevis } = devisSlice.actions
export default devisSlice.reducer;


