/* eslint-disable import/order */
/* eslint-disable @typescript-eslint/consistent-type-imports */
import { createSlice, type PayloadAction } from "@reduxjs/toolkit";
import { fournisseurState } from "./type";
import { Fournisseur } from "@/types/fournisseurType";
import { addFournisseur, getFournisseurs, updateFournisseur } from "./thunk";
import { addContactFournisseur, updateContactFournisseur } from "../contact/thunk";
import { Contacts } from "@/types/clientType";

const initialState: fournisseurState = {
    status: "idle",
    error: null,
    fournisseurs: [],
    fournisseurSelected: null,
};

const fournisseurSlice = createSlice({
  name: "fournisseur",
  initialState,
  reducers: {
    selectfournisseur: (state, action: PayloadAction<Fournisseur>) => {
      state.fournisseurSelected = action.payload;
    }
  },
  extraReducers: (builder) => {


  /**
   * get all fournisseurs
   */
    builder.addCase(getFournisseurs.fulfilled, (state, action) => {
      const data = action.payload;

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

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

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



  /**
   * add fournisseur
   */
    builder.addCase(addFournisseur.fulfilled, (state, action) => {
      const { data, success } = action.payload as any
      
      if(success){
        state.fournisseurs.push(data);
      }
      state.status = "succeeded";
      state.error = null;
    });

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

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


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

    builder.addCase(updateFournisseur.fulfilled, (state, action) => {
      console.log("action.payload : ",action.payload);
      
      const { fournisseur, success } = action.payload as unknown as { success: boolean; fournisseur: Fournisseur };
      
      if (success && fournisseur?.numero) {
        const idx = state.fournisseurs.findIndex((p) => p.numero === fournisseur.numero);

         if (idx !== -1) {
          const oldItem = state.fournisseurs[idx];

          state.fournisseurs[idx] = {
            ...oldItem, 
            intitule: fournisseur.intitule,
            adresse: fournisseur.adresse,
            code_postal: fournisseur.code_postal,
            ville: fournisseur.ville,
            telephone: fournisseur.telephone,
            email: fournisseur.email,
            siret: fournisseur.siret,
            tva_intra: fournisseur.tva_intra,
            code_naf: fournisseur.code_naf,
          };
        }

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

    builder.addCase(updateFournisseur.rejected, (state, action) => {
      state.status = "failed";
      state.error = (action.payload as string) || action.error.message || "Failed to update";
    });


     /**
     * create contact Fournisseur
     */
    builder.addCase(addContactFournisseur.pending, (state) => {
      state.status = "loading";
    });

    builder.addCase(addContactFournisseur.fulfilled, (state, action) => {
      const payload = action.payload as Contacts;
      const idx = state.fournisseurs.findIndex((n) => n.numero === payload.numero);
      if (idx !== -1) {
        state.fournisseurs[idx].contacts?.unshift(payload);
      } 

      if (state.fournisseurSelected?.numero === payload.numero) {
        state.fournisseurSelected.contacts?.unshift(payload)
      }

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

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



    /**
     * update contact Fournisseur
     */
    builder.addCase(updateContactFournisseur.pending, (state) => {
      state.status = "loading";
    });

    builder.addCase(updateContactFournisseur.fulfilled, (state, action) => {
      const payload = action.payload as Contacts;
      const idx = state.fournisseurs.findIndex((n) => n.numero === payload.numero);
      if (idx !== -1) {
        const idxContact = state.fournisseurs[idx].contacts?.findIndex((n) => n.contact_numero === payload.contact_numero);
        if (idxContact !== -1) {
            state.fournisseurs[idx].contacts![idxContact || 0] = payload
        }
      } 

      if (state.fournisseurSelected?.numero === payload.numero) {
        const idxContact = state.fournisseurSelected.contacts?.findIndex((n) => n.contact_numero === payload.contact_numero);
          if (idxContact !== -1) {
            state.fournisseurSelected.contacts![idxContact || 0] = payload
        }
      }

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

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

  },
});


export const { selectfournisseur } = fournisseurSlice.actions
export default fournisseurSlice.reducer;


