'use client';
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import { getDashboardSourceQuality, getDashboardStatistics, getDashboardCallingStatics, getDashboardHiddenStats, getDashboardWeekStatistics, getSourceEfficiency, getSourceEfficiencyTeamLead, getSourceQualityTeamLead, getSourceQualityOverall } from './service';
import { DashboardFilter, DashboardState } from './interface';
import { extractUniqueKeys, getHighestValue } from './utils/helper';
import moment from 'moment';
import { createSlug, removeEmptyKeys } from '@/utills/helper';
const dateFormat = 'YYYY-MM-DD';
export const dashboardFilter = {
  start_date: moment().format(dateFormat),
  end_date: moment().format(dateFormat),
  locality: '', // Locality filter added
};
const initialState: DashboardState = {
  dashboardStatistics: {
    activeCount: 0,
    bookedCount: 0,
    businessDone: 0,
    deadCount: 0,
    OBMDoneCount: 0,
    OBMDoneTotal: 0,
    overdueCount: 0,
    scheduledCount: 0,
    todayCallingCount: 0,
    todayFollowUpCount: 0,
    tokenDoneCount: 0,
    tokenDoneTotal: 0,
    totalAllCount: 0,
    vcDoneCount: 0,
    vcDoneTotal: 0,
    vcDoneDuplicate: 0,
    visitedCountAll: 0,
    visitedDuplicate: 0,
    visitedRepeatVisit: 0,
    siteVisitDone: 0,
    siteVisitDoneTotal: 0,
    siteVisitDoneDuplicate: 0,
    OBMDoneDuplicate: 0,
    tokenDoneDuplicate: 0,
    bookedDuplicate: 0,
  },
  dashboardCallingStatics :{
    leadWeekAverage : 0,
    dateWiseCallLeads: [],
  },
  dashboardHiddenStatics:{
    totalAllCount: 0,
    deadCount: 0,
    businessDone: 0,
  },
  dashboardFilter,
  statisticsStatus: 'loading',
  dashboardCallingStaticsStatus: 'loading',
  dashboardHiddenStaticsStatus: 'loading',
  dashboardWeekStatistics: {},
  weekStatisticsStatus: 'loading',

  dashboardSourceQualityTab: 'visited',
  dashboardSourceQuality: [],
  dashboardSourceQualityGraphData: [],
  dashboardSourceQualityTableHeader: [],
  dashboardSourceQualityStatus: 'loading',
  dashboardSourceQualityPercentages: [],

  sourceQualityTeamLead: [],
  sourceQualityTeamLeadGraphData: [],
  sourceQualityTeamLeadTableHeader: [],
  sourceQualityTeamLeadStatus: 'loading',
  sourceQualityTeamLeadPercentages: [],
  sourceQualityTeamLeadFilter: {},

  sourceQualityOverallTab: 'visited',
  sourceQualityOverallData: [],
  sourceQualityOverallStatus: 'loading',

  sourceEfficiencyTab: 'visited',
  sourceEfficiencyData: [],
  sourceEfficiencyTableHeader: [],
  sourceEfficiencyStatus: 'loading',
  sourceEfficiencyFilter: {},
  sourceEfficiencyTeamLeadData: [],
  sourceEfficiencyTeamLeadTableHeader: [],
  sourceEfficiencyTeamLeadStatus: 'loading',
  sourceEfficiencyTeamLeadFilter: {},

  status: 'loading',

  sourceQualityData: [],
  sourceQualityStatus: 'loading',
  sourceQualityGraphData: [],
  sourceQualityTableHeader: [],
  error: null,
};

const removeDates = (filter: DashboardFilter) =>{
  delete filter?.start_date;
  delete filter?.end_date;
  return filter;
};

export const fetchDashboardStatistics = createAsyncThunk('dashboard/fetchDashboardStatistics', async(data: any = {}, { getState }) => {
  const state: any = await getState();
  const filter = { ...state.dashboard.dashboardFilter, ...data };
  const queryString = removeEmptyKeys(filter); // Remove Empty filters before api call
  const dashboardStatistics = await getDashboardStatistics(removeDates(queryString));
  return dashboardStatistics.data;
});

export const fetchDashboardCallingStatistics = createAsyncThunk('dashboard/fetchDashboardCallingStatistics', async(data: any = {}, { getState }) => {
  const state: any = await getState();
  const filter = { ...state.dashboard.dashboardFilter, ...data };
  const queryString = removeEmptyKeys(filter); // Remove Empty filters before api call
  const dashboardCallingStatics = await getDashboardCallingStatics(removeDates(queryString));
  return dashboardCallingStatics.data;
});

export const fetchDashboardHiddenStats = createAsyncThunk('dashboard/fetchDashboardHiddenStats', async(data: any = {}, { getState }) => {
  const state: any = await getState();
  const filter = { ...state.dashboard.dashboardFilter, ...data };
  const queryString = removeEmptyKeys(filter); // Remove Empty filters before api call
  const dashboardHiddenStatics = await getDashboardHiddenStats(removeDates(queryString));
  return dashboardHiddenStatics.data;
})

export const fetchDashboardWeekStatistics = createAsyncThunk('dashboard/fetchDashboardWeekStatistics', async(data: any = {}, { getState }) => {
  const state: any = await getState();
  const filter = { ...state.dashboard.dashboardFilter, ...data };
  const queryString = removeEmptyKeys(filter); // Remove Empty filters before api call
  const dashboardWeekStatistics = await getDashboardWeekStatistics(removeDates(queryString));
  return dashboardWeekStatistics.data;
});

export const fetchDashboardSourceQuality = createAsyncThunk('dashboard/fetchDashboardSourceQuality', async({ ..._ }: any = {}, { getState }) => {
  const state: any = await getState();
  const filter = { ...state.dashboard.dashboardFilter, tab_key: state.dashboard.dashboardSourceQualityTab };
  const queryString = removeEmptyKeys(filter); // Remove Empty filters before api call
  const dashboardSourceQuality = await getDashboardSourceQuality(removeDates(queryString));
  return dashboardSourceQuality.data;
});

export const fetchSourceQualityTeamLead = createAsyncThunk('dashboard/fetchSourceQualityTeamLead', async({ ..._ }: any = {}, { getState }) => {
  const state: any = await getState();
  const filter = { ...state.dashboard.dashboardFilter, tab_key: state.dashboard.dashboardSourceQualityTab };
  const queryString = removeEmptyKeys(filter); // Remove Empty filters before api call
  const sourceQualityTeamLead = await getSourceQualityTeamLead(removeDates(queryString));
  return sourceQualityTeamLead.data;
});

// Source Quality Overall: aggregate bar-chart data (counts by source only).
// Unlike fetchDashboardSourceQuality, start_date/end_date are NOT stripped —
// this widget has its own working date filter, independent of dashboardFilter's
// dates (which the other dashboard APIs deliberately ignore). The launch_id
// (and other drill-down filters) still come straight from dashboardFilter, so
// the launch dropdown above the dashboard applies to this widget directly.
export const fetchSourceQualityOverall = createAsyncThunk('dashboard/fetchSourceQualityOverall', async(data: { start_date?: string; end_date?: string } = {}, { getState }) => {
  const state: any = await getState();
  const filter = {
    launch_id: state.dashboard.dashboardFilter.launch_id,
    lead_user_city_id: state.dashboard.dashboardFilter.lead_user_city_id,
    lead_user_id: state.dashboard.dashboardFilter.lead_user_id,
    lead_user_role_name: state.dashboard.dashboardFilter.lead_user_role_name,
    veiw_data: state.dashboard.dashboardFilter.veiw_data,
    tab_key: state.dashboard.sourceQualityOverallTab,
    ...data,
  };
  const queryString = removeEmptyKeys(filter);
  const sourceQualityOverall = await getSourceQualityOverall(queryString);
  return sourceQualityOverall.data;
});

export const fetchSourceEfficiency = createAsyncThunk('dashboard/fetchSourceEfficiency', async(data: any = {}, { getState }) => {
  const state: any = await getState();
  const filter = { ...data, ...state.dashboard.dashboardFilter, tab_key: state.dashboard.sourceEfficiencyTab };
  const queryString = removeEmptyKeys(filter); // Remove Empty filters before api call
  const sourceEfficiencyData = await getSourceEfficiency(removeDates(queryString));
  return sourceEfficiencyData.data;
});

export const fetchSourceEfficiencyTeamLead = createAsyncThunk('dashboard/fetchSourceEfficiencyTeamLead', async(data: any = {}, { getState }) => {
  const state: any = await getState();
  const filter = { ...data, ...state.dashboard.dashboardFilter, tab_key: state.dashboard.sourceEfficiencyTab };
  const queryString = removeEmptyKeys(filter); // Remove Empty filters before api call
  const sourceEfficiencyTeamLeadData = await getSourceEfficiencyTeamLead(removeDates(queryString));
  return sourceEfficiencyTeamLeadData.data;
});

const dashboardSlice = createSlice({
  name: 'dashboard',
  initialState,
  reducers: {
    setSourceQualityTabs:  (state, action) => {
      state.dashboardSourceQualityTab = action.payload;
    },
    setSourceEfficiencyTab:  (state, action) => {
      state.sourceEfficiencyTab = action.payload;
    },
    setSourceQualityOverallTab:  (state, action) => {
      state.sourceQualityOverallTab = action.payload;
    },
    setDashboardFilter:  (state, action) => {
      state.dashboardFilter = { ...state.dashboardFilter, ...action.payload };
    },
    resetDashboardFilter:  (state, action) => {
      state.statisticsStatus = 'loading';
      state.dashboardFilter = action.payload;
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchDashboardStatistics.pending, (state, action) => {
        state.statisticsStatus = 'loading';
        state.dashboardFilter = { ...state.dashboardFilter, ...action.meta.arg };
      })
      .addCase(fetchDashboardStatistics.fulfilled, (state, action) => {
        state.statisticsStatus = 'succeeded';
        state.dashboardStatistics = action.payload;
      })
      .addCase(fetchDashboardStatistics.rejected, (state, action: any) => {
        state.statisticsStatus = 'failed';
        state.error = action.error.message;
      })

      .addCase(fetchDashboardCallingStatistics.pending, (state) => {
        state.dashboardCallingStaticsStatus = 'loading';
      })
      .addCase(fetchDashboardCallingStatistics.fulfilled, (state, action) => {
        state.dashboardCallingStaticsStatus = 'succeeded';
        state.dashboardCallingStatics = {
          leadWeekAverage: action.payload.leadWeekAverage,
          dateWiseCallLeads: action.payload.dateWiseCallLeads,
        };
      })
      .addCase(fetchDashboardCallingStatistics.rejected, (state, action: any) => {
        state.dashboardCallingStaticsStatus = 'failed';
        state.error = action.error.message;
      })

      .addCase(fetchDashboardHiddenStats.pending, (state) => {
        state.dashboardHiddenStaticsStatus = 'loading';
      })
      .addCase(fetchDashboardHiddenStats.fulfilled, (state, action) => {
        state.dashboardHiddenStaticsStatus = 'succeeded';
        state.dashboardHiddenStatics = {
          totalAllCount: action.payload.totalAllCount,
          deadCount: action.payload.deadCount,
          businessDone: action.payload.businessDone,
        };
      })
      .addCase(fetchDashboardHiddenStats.rejected, (state, action: any) => {
        state.dashboardHiddenStaticsStatus = 'failed';
        state.error = action.error.message;
      })

      .addCase(fetchDashboardWeekStatistics.pending, (state) => {
        state.weekStatisticsStatus = 'loading';
      })
      .addCase(fetchDashboardWeekStatistics.fulfilled, (state, action) => {
        state.weekStatisticsStatus = 'succeeded';
        state.dashboardWeekStatistics = action.payload;
      })
      .addCase(fetchDashboardWeekStatistics.rejected, (state, action: any) => {
        state.weekStatisticsStatus = 'failed';
        state.error = action.error.message;
      })

      .addCase(fetchDashboardSourceQuality.pending, (state, action) => {
        state.dashboardSourceQualityStatus = 'loading';
        state.dashboardFilter = { ...state.dashboardFilter, ...action.meta.arg };
      })
      .addCase(fetchDashboardSourceQuality.fulfilled, (state, action) => {
        state.dashboardSourceQualityStatus = 'succeeded';
        state.dashboardSourceQuality = action.payload.data;

        if (state.dashboardSourceQuality?.length > 0) {
          // Get unique keys for table header
          // Assuming state.dashboardSourceQuality is an array of objects with keys like 'launch_name', 'manual', 'facebook', etc.
          const allKeys: string[] = state.dashboardSourceQuality.reduce((keys: string[], obj: any) => {
            Object.keys(obj).forEach(key => {
              if (!keys.includes(key)) {
                keys.push(key);
              }
            });
            return keys;
          }, []);
          // Filter out non-essential keys
          const filteredKeys: string[] = allKeys.filter(key => key !== 'launch_name' && key !== 'totalLeadCount');
          // Convert filteredKeys into an array of objects with desired format
          const filteredKeyObjects = filteredKeys.map(key => ({
            title: key.split('-').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join('-'), // Capitalize the first letter of the key
            dataIndex: createSlug(key),
            key: key,
            align: 'center', // Or set the alignment as needed
            width: 150, // Or set the width as needed
          }));
          state.dashboardSourceQualityTableHeader = filteredKeyObjects;

          // Transform source quality data
          const graphData = state.dashboardSourceQuality.flatMap(
            ({ launch_name, ...rest }: { launch_name: any; [key: string]: number }) => {
              return Object.entries(rest)
                .filter(([type]) => type !== 'totalLeadCount') // Filter out 'totalLeadCount'
                .map(([type, launchs]) => ({
                  key: Math.random(),
                  name: launch_name,
                  name_key: createSlug(launch_name),
                  type: type
                    .split('-')
                    .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
                    .join('-'),
                  launchs,
                }));
            }
          );
          state.dashboardSourceQualityGraphData = graphData;

          const highestPercentages: { [key: string]: number } = {};

          // Calculate percentages and track highest percentages
          const dataWithPercentages = state.dashboardSourceQuality.map(({ launch_name, ...rest }: { launch_name: string, [key: string]: any }) => {
            const totalLeadCount = Number(rest.totalLeadCount);

            Object.keys(rest).forEach(key => {
              if (key !== 'launch_name' && key !== 'totalLeadCount') {
                const fieldVal = Number(rest[key]);
                const percentage = (fieldVal / totalLeadCount) * 100;

                // Update highest percentages for each key
                if (percentage > (highestPercentages[createSlug(key)] || 0)) {
                  highestPercentages[createSlug(key)] = percentage;
                }
              }
            });

            return { launch_name, ...rest };
          });
          const dataWithHighlightedPercentages = dataWithPercentages.map(({ launch_name, ...rest }: { launch_name: string, [key: string]: any }) => {
            const totalLeadCount = Number(rest.totalLeadCount);

            Object.keys(rest).forEach(key => {
              if (key !== 'launch_name' && key !== 'totalLeadCount') {
                const fieldVal = Number(rest[key]);
                const percentage = ((fieldVal / totalLeadCount) * 100).toFixed(2) + '%';
                const numericPercentage = (fieldVal / totalLeadCount) * 100;

                rest[createSlug(key)] = {
                  value: percentage,
                  color: numericPercentage === highestPercentages[createSlug(key)] ? 'green' : '', // Highlight the highest percentage
                };
              }
            });

            return { launch_name, ...rest, key: launch_name };
          });
          // Update state with highlighted data
          state.dashboardSourceQuality = dataWithHighlightedPercentages;
        } else {
          state.dashboardSourceQualityGraphData = [];
          state.dashboardSourceQualityTableHeader = [];
          state.dashboardSourceQuality = [];
        }
      })
      .addCase(fetchDashboardSourceQuality.rejected, (state, action: any) => {
        state.dashboardSourceQualityStatus = 'failed';
        state.error = action.error.message;
      })

      // Source Quality Team Lead Cases
      .addCase(fetchSourceQualityTeamLead.pending, (state, action) => {
        state.sourceQualityTeamLeadStatus = 'loading';
        state.sourceQualityTeamLeadFilter = { ...state.sourceQualityTeamLeadFilter, ...action.meta.arg };
      })
      .addCase(fetchSourceQualityTeamLead.fulfilled, (state, action) => {
        state.sourceQualityTeamLeadStatus = 'succeeded';
        state.sourceQualityTeamLead = action.payload.data;

        if (state.sourceQualityTeamLead?.length > 0) {
          // Get unique keys for table header
          // Assuming state.sourceQualityTeamLead is an array of objects with keys like 'project_name', 'manual', 'facebook', etc.
          const allKeys: string[] = state.sourceQualityTeamLead.reduce((keys: string[], obj: any) => {
            Object.keys(obj).forEach(key => {
              if (!keys.includes(key)) {
                keys.push(key);
              }
            });
            return keys;
          }, []);

          // Filter out non-essential keys
          const filteredKeys: string[] = allKeys.filter(key => key !== 'project_name'  && key !== 'totalLeadCount');

          // Convert filteredKeys into an array of objects with desired format
          const filteredKeyObjects = filteredKeys.map(key => ({
            title: key.split('-').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join('-'), // Capitalize the first letter of the key
            dataIndex: key,
            key: key,
            align: 'center', // Or set the alignment as needed
            width: 150, // Or set the width as needed
          }));

          state.sourceQualityTeamLeadTableHeader = filteredKeyObjects;

          // Transform source quality data
          const graphData = state.sourceQualityTeamLead.flatMap(
            ({
              project_name,
              ...rest
            }: {
                project_name: any
                [key: string]: number
            }) => {
              return Object.entries(rest)
                .filter(([type]) => type !== 'totalLeadCount') // Exclude 'totalLeadCount'
                .map(([type, launchs]) => ({
                  name: project_name,
                  type: type
                    .split('-')
                    .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
                    .join('-'),
                  launchs,
                }));
            }
          );
          state.sourceQualityTeamLeadGraphData = graphData;

          // Calculate percentages for each key in every object
          const highestPercentages: { [key: string]: number } = {};

          // First pass: Calculate percentages and track highest percentages
          const dataWithPercentages = state.sourceQualityTeamLead.map(({ project_name, ...rest }: { project_name: any, [key: string]: any }) => {
            const totalLeadCount = Number(rest.totalLeadCount);
            const obj = { ...rest }; // Create a copy of rest to avoid mutating the original object

            Object.keys(rest).forEach(key => {
              if (key !== 'project_name' && key !== 'totalLeadCount') {
                const fieldVal: number = Number(rest[key]);
                const percentage = (fieldVal / totalLeadCount) * 100;

                // Update highest percentages for each key
                if (percentage > (highestPercentages[key] || 0)) {
                  highestPercentages[key] = percentage;
                }
              }
            });

            return { project_name, ...obj };
          });
          const dataWithHighlightedPercentages = dataWithPercentages.map(({ project_name, ...rest }: { project_name: any, [key: string]: any }) => {
            const totalLeadCount = Number(rest.totalLeadCount);
            const obj = { ...rest }; // Create a copy of rest to avoid mutating the original object

            Object.keys(rest).forEach(key => {
              if (key !== 'project_name' && key !== 'totalLeadCount') {
                const fieldVal: number = Number(rest[key]);
                const percentage = ((fieldVal / totalLeadCount) * 100).toFixed(2) + '%';
                const numericPercentage = (fieldVal / totalLeadCount) * 100;

                obj[key] = {
                  value: percentage,
                  color: numericPercentage === highestPercentages[key] ? 'green' : '', // Highlight the highest percentage
                };
              }
            });

            return { project_name, ...obj };
          });
          state.sourceQualityTeamLead = dataWithHighlightedPercentages;
        } else {
          state.sourceQualityTeamLeadGraphData = [];
          state.sourceQualityTeamLeadTableHeader = [];
          state.sourceQualityTeamLead = [];
        }
      })
      .addCase(fetchSourceQualityTeamLead.rejected, (state, action: any) => {
        state.sourceQualityTeamLeadStatus = 'failed';
        state.error = action.error.message;
      })

      // Source Quality Overall Cases
      .addCase(fetchSourceQualityOverall.pending, (state) => {
        state.sourceQualityOverallStatus = 'loading';
      })
      .addCase(fetchSourceQualityOverall.fulfilled, (state, action) => {
        state.sourceQualityOverallStatus = 'succeeded';
        state.sourceQualityOverallData = action.payload.data || [];
      })
      .addCase(fetchSourceQualityOverall.rejected, (state, action: any) => {
        state.sourceQualityOverallStatus = 'failed';
        state.error = action.error.message;
      })

      // Source Efficiency Cases
      .addCase(fetchSourceEfficiency.pending, (state) => {
        state.sourceEfficiencyStatus = 'loading';
      })
      .addCase(fetchSourceEfficiency.fulfilled, (state, action) => {
        state.sourceEfficiencyStatus = 'succeeded';
        state.sourceEfficiencyData = action.payload.data;
        if (state.sourceEfficiencyData?.length > 0) {
          const updatedData: string[] = state.sourceEfficiencyData.map((obj: any) => {
            const dataObj: any = {};
            obj.map((key: any) => {
              dataObj.launch_name = key.launch_name;
              dataObj.locality = key.locality;    // To set locality for each launches
              dataObj[key.source] = ((key.source_count / key.total_count) * 100).toFixed(2);
              dataObj[`${key.source}_total_count`] = key.total_count;
            });
            return dataObj;
          });
          const allKeys: string[] = extractUniqueKeys(updatedData);

          // Filter out non-essential keys
          const filteredKeys: string[] = allKeys.filter(key => key !== 'launch_name' && !key.endsWith('_total_count'));

          // Convert filteredKeys into an array of objects with desired format
          const filteredKeyObjects = filteredKeys.map(key => ({
            title: key.split('-').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join('-'), // Capitalize the first letter of the key
            dataIndex: key,
            key: key,
            align: 'center', // Or set the alignment as needed
            width: 150, // Or set the width as needed
          }));
          const highestValue = getHighestValue(updatedData, 'launch_name');
          state.sourceEfficiencyTableHeader = filteredKeyObjects;

          // // Calculate percentages for each key in every object
          const dataWithPercentages = updatedData.map((rest:any) => {
            const obj = rest;
            Object.keys(rest).forEach(key => {
              if (key !== 'launch_name' && !key.endsWith('_total_count') && key !== 'locality') {
                const fieldVal: number = Number(obj[key]);
                obj[key] = {
                  value: fieldVal + '%',
                  color: (fieldVal >= highestValue[key] && fieldVal != 0) ? 'green' : '',
                };
              }
            });
            return { ...rest, ...obj };
          });
          state.sourceEfficiencyData = updatedData;

        } else {
          state.sourceEfficiencyTableHeader = [];
          state.sourceEfficiencyData = [];
        }
      })
      .addCase(fetchSourceEfficiency.rejected, (state, action: any) => {
        state.sourceEfficiencyStatus = 'failed';
        state.error = action.error.message;
      })

      // Source Efficiency Team Lead Cases
      .addCase(fetchSourceEfficiencyTeamLead.pending, (state) => {
        state.sourceEfficiencyTeamLeadStatus = 'loading';
      })
      .addCase(fetchSourceEfficiencyTeamLead.fulfilled, (state, action) => {
        state.sourceEfficiencyTeamLeadStatus = 'succeeded';
        state.sourceEfficiencyTeamLeadData = action.payload.data;
        if (state.sourceEfficiencyTeamLeadData?.length > 0) {
          const updatedData: string[] = state.sourceEfficiencyTeamLeadData.map((obj: any) => {
            const dataObj: any = {};
            obj.map((key: any) => {
              dataObj.project_name = key.project_name;
              dataObj[key.source] = ((key.source_count / key.total_count) * 100).toFixed(2);
              dataObj[`${key.source}_total_count`] = key.total_count;
            });
            return dataObj;
          });

          const allKeys: string[] = extractUniqueKeys(updatedData);

          // Filter out non-essential keys
          const filteredKeys: string[] = allKeys.filter(key => key !== 'project_name' && !key.endsWith('_total_count'));

          // Convert filteredKeys into an array of objects with desired format
          const filteredKeyObjects = filteredKeys.map(key => ({
            title:  key.split('-').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join('-'), // Capitalize the first letter of the key
            dataIndex: key,
            key: key,
            align: 'center', // Or set the alignment as needed
            width: 150, // Or set the width as needed
          }));

          const highestValue = getHighestValue(updatedData, 'project_name');
          state.sourceEfficiencyTeamLeadTableHeader = filteredKeyObjects;

          // // Calculate percentages for each key in every object
          const dataWithPercentages = updatedData.map((rest:any) => {
            const obj = rest;
            Object.keys(rest).forEach(key => {
              if (key !== 'project_name' && !key.endsWith('_total_count')) {
                const fieldVal: number = Number(obj[key]);
                obj[key] = {
                  value: fieldVal + '%',
                  color: (fieldVal >= highestValue[key] && fieldVal != 0) ? 'green' : '',
                };
              }
            });
            return { ...rest, ...obj };
          });
          state.sourceEfficiencyTeamLeadData = updatedData;

        } else {
          state.sourceEfficiencyTeamLeadTableHeader = [];
          state.sourceEfficiencyTeamLeadData = [];
        }
      })
      .addCase(fetchSourceEfficiencyTeamLead.rejected, (state, action: any) => {
        state.sourceEfficiencyTeamLeadStatus = 'failed';
        state.error = action.error.message;
      });

  },
});

export const { setSourceQualityTabs, setDashboardFilter, resetDashboardFilter, setSourceEfficiencyTab, setSourceQualityOverallTab } = dashboardSlice.actions;

export default dashboardSlice.reducer;
