// import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
// import { RootState } from "./store";

// // Common interface for status counts
// interface StatusCounts {
//   [key: string]: number;
// }

// // Record Officer Summary interface
// interface RecordSummary {
//   totalIncoming: number;
//   totalOutgoing: number;
//   monthlyIncoming: number;
//   monthlyOutgoing: number;
//   weeklyIncoming: number;
//   weeklyOutgoing: number;
//   dailyIncoming: number;
//   dailyOutgoing: number;
//   lastUpdated?: number;
// }

// // Combined Dashboard State
// interface DashboardState {
//   // User Dashboard state
//   totalOutgoing: number;
//   totalIncoming: number;
//   internalIncoming: number;
//   externalIncoming: number;
//   totalCC: number;
//   outgoingStats: StatusCounts;
//   incomingStats: StatusCounts;
//   approvalStats: StatusCounts;
//   userDashboardStatus: "idle" | "loading" | "failed" | "succeeded";
//   lastUpdated: number;

//   // Record Officer Dashboard state
//   recordSummary: RecordSummary | null;
//   recordOfficerLoading: boolean;
//   recordOfficerError: string | null;
//   recordOfficerLastUpdated: number;
// }

// const initialState: DashboardState = {
//   // User Dashboard initial state
//   totalOutgoing: 0,
//   totalIncoming: 0,
//   internalIncoming: 0,
//   externalIncoming: 0,
//   totalCC: 0,
//   outgoingStats: {
//     Draft: 0,
//     Forward: 0,
//     Accepted: 0,
//     Approved: 0,
//     Rejected: 0,
//     Adjusted: 0,
//     Sent: 0,
//   },
//   incomingStats: {
//     "In Progress": 0,
//     Accepted: 0,
//     Reassigned: 0,
//   },
//   approvalStats: {
//     Pending: 0,
//     Approved: 0,
//     Rejected: 0,
//   },
//   userDashboardStatus: "idle",
//   lastUpdated: 0,

//   // Record Officer Dashboard initial state
//   recordSummary: null,
//   recordOfficerLoading: false,
//   recordOfficerError: null,
//   recordOfficerLastUpdated: 0,
// };

// // Get date ranges for filtering
// const getDateRanges = () => {
//   const today = new Date();
//   const startOfDay = new Date(
//     today.getFullYear(),
//     today.getMonth(),
//     today.getDate()
//   ).toISOString();

//   // Get start of week (Sunday)
//   const startOfWeek = new Date(today);
//   startOfWeek.setDate(today.getDate() - today.getDay());
//   startOfWeek.setHours(0, 0, 0, 0);

//   // Get start of month
//   const startOfMonth = new Date(
//     today.getFullYear(),
//     today.getMonth(),
//     1
//   ).toISOString();

//   return {
//     startOfDay,
//     startOfWeek: startOfWeek.toISOString(),
//     startOfMonth,
//   };
// };

// // User Dashboard async thunk with optimized performance
// export const fetchDashboardStats = createAsyncThunk(
//   "dashboard/fetchStats",
//   async (userName: string, { getState }) => {
//     try {
//       const state = getState() as RootState;
//       const lastUpdated = state.dashboard?.lastUpdated;
//       const now = Date.now();

//       // Cache for 2 minutes to reduce API calls while maintaining reasonable freshness
//       if (lastUpdated && now - lastUpdated < 120000) {
//        
//         return null; // Return null to skip updating state
//       }

//     
//       // Prepare base filter with username
//       const baseFilter = `Author/Title eq '${userName}' and Is_Deleted eq 0`;

//       try {
//         // Parallel queries for different data needs
//         const [
//           // Total counts by record type - outgoing
//           outgoingCount,
//           // Total counts by record type - incoming
//           incomingCount,
//           // Get outgoing records with statuses
//           outgoingRecords,
//           // Get incoming records with statuses
//           incomingRecords,
//           // Get records with CC info
//           ccRecords,
//           // Get records that need approval
//           approvalRecords,
//         ] = await Promise.all([
//           // Count queries
//           userRecordsService?.getFilteredCount(
//             `${baseFilter} and Record_Type eq 'Outgoing'`
//           ),
//           userRecordsService?.getFilteredCount(
//             `${baseFilter} and Record_Type eq 'Incoming'`
//           ),

//           // Status detail queries - limited fields and counts
//           userRecordsService?.getFilteredItems(
//             `${baseFilter} and Record_Type eq 'Outgoing'`,
//             ["Status"],
//             [],
//             100,
//             "Created",
//             "desc"
//           ),
//           userRecordsService.getFilteredItems(
//             `${baseFilter} and Record_Type eq 'Incoming'`,
//             ["Status", "Organization_Name"],
//             [],
//             100,
//             "Created",
//             "desc"
//           ),

//           // CC info query
//           userRecordsService.getFilteredCount(
//             `${baseFilter} and (Internal_CC eq 1 or CC_Organization_Name ne null)`
//           ),

//           // Approval query
//           userRecordsService.getFilteredItems(
//             `${baseFilter} and Needs_Approval eq 1`,
//             ["Approval_Status"],
//             [],
//             100,
//             "Created",
//             "desc"
//           ),
//         ]);

//         // Process status counts with less client-side computation
//         const outgoingStats: StatusCounts = {
//           Draft: 0,
//           Forward: 0,
//           Accepted: 0,
//           Approved: 0,
//           Rejected: 0,
//           Adjusted: 0,
//           Sent: 0,
//         };
//         outgoingRecords.forEach((record: any) => {
//           const status = record.Status || "Unknown";
//           outgoingStats[status] = (outgoingStats[status] || 0) + 1;
//         });

//         const incomingStats: StatusCounts = {
//           "In Progress": 0,
//           Accepted: 0,
//           Reassigned: 0,
//         };
//         incomingRecords.forEach((record: any) => {
//           const status = record.Status || "Unknown";
//           incomingStats[status] = (incomingStats[status] || 0) + 1;
//         });

//         // Count internal vs external incoming
//         const internalIncoming = incomingRecords.filter(
//           (r: any) => !r.Organization_Name || r.Organization_Name === ""
//         ).length;

//         const externalIncoming = incomingRecords.filter(
//           (r: any) => r.Organization_Name && r.Organization_Name !== ""
//         ).length;

//         // Process approval stats
//         const approvalStats: StatusCounts = {
//           Pending: 0,
//           Approved: 0,
//           Rejected: 0,
//         };

//         approvalRecords.forEach((record: any) => {
//           const status = record.Approval_Status || "Pending";
//           approvalStats[status] = (approvalStats[status] || 0) + 1;
//         });

//         return {
//           totalOutgoing: outgoingCount,
//           totalIncoming: incomingCount,
//           internalIncoming,
//           externalIncoming,
//           totalCC: ccRecords,
//           outgoingStats,
//           incomingStats,
//           approvalStats,
//           lastUpdated: now,
//         };
//       } catch (error) {
//         console.error("Error fetching dashboard data from SharePoint:", error);
//         // Return mock data for charts to be visible
//         return {
//           totalOutgoing: 5,
//           totalIncoming: 13,
//           internalIncoming: 6,
//           externalIncoming: 7,
//           totalCC: 3,
//           outgoingStats: {
//             Draft: 2,
//             Forward: 1,
//             Accepted: 0,
//             Approved: 0,
//             Rejected: 0,
//             Adjusted: 0,
//             Sent: 2,
//           },
//           incomingStats: {
//             "In Progress": 8,
//             Accepted: 3,
//             Reassigned: 2,
//           },
//           approvalStats: {
//             Pending: 5,
//             Approved: 8,
//             Rejected: 2,
//           },
//           lastUpdated: now,
//         };
//       }
//     } catch (error) {
//       console.error("Error in fetchDashboardStats:", error);
//       throw error;
//     }
//   }
// );

// // Record Officer Dashboard async thunk with optimized real-time fetching
// export const fetchRecordOfficerStats = createAsyncThunk(
//   "dashboard/fetchRecordOfficerStats",
//   async (_, { getState }) => {
//     try {
//       const state = getState() as RootState;
//       const lastUpdated = state.dashboard.recordOfficerLastUpdated;
//       const now = Date.now();

//       // Cache for 2 minutes to reduce API calls
//       if (lastUpdated && now - lastUpdated < 120000) {
//         return null; // Return null to skip updating state
//       }


//       // Get date ranges for filtering
//       const { startOfDay, startOfWeek, startOfMonth } = getDateRanges();

//       try {
//         // Use server-side filtering and optimized queries
//         const queries = [
//           // Total counts with server-side filtering by Record_Type
//           recordsService.getFilteredCount(
//             "Is_Deleted eq 0 and Record_Type eq 'Incoming'"
//           ),
//           recordsService.getFilteredCount(
//             "Is_Deleted eq 0 and Record_Type eq 'Outgoing'"
//           ),

//           // Monthly counts with server-side filtering
//           recordsService.getFilteredCount(
//             `Is_Deleted eq 0 and Record_Type eq 'Incoming' and Created ge datetime'${startOfMonth}'`
//           ),
//           recordsService.getFilteredCount(
//             `Is_Deleted eq 0 and Record_Type eq 'Outgoing' and Created ge datetime'${startOfMonth}'`
//           ),

//           // Weekly counts with server-side filtering
//           recordsService.getFilteredCount(
//             `Is_Deleted eq 0 and Record_Type eq 'Incoming' and Created ge datetime'${startOfWeek}'`
//           ),
//           recordsService.getFilteredCount(
//             `Is_Deleted eq 0 and Record_Type eq 'Outgoing' and Created ge datetime'${startOfWeek}'`
//           ),

//           // Daily counts with server-side filtering
//           recordsService.getFilteredCount(
//             `Is_Deleted eq 0 and Record_Type eq 'Incoming' and Created ge datetime'${startOfDay}'`
//           ),
//           recordsService.getFilteredCount(
//             `Is_Deleted eq 0 and Record_Type eq 'Outgoing' and Created ge datetime'${startOfDay}'`
//           ),
//         ];

//         // Execute all count queries in parallel for maximum performance
//         const [
//           totalIncoming,
//           totalOutgoing,
//           monthlyIncoming,
//           monthlyOutgoing,
//           weeklyIncoming,
//           weeklyOutgoing,
//           dailyIncoming,
//           dailyOutgoing,
//         ] = await Promise.all(queries);

//         return {
//           totalIncoming,
//           totalOutgoing,
//           monthlyIncoming,
//           monthlyOutgoing,
//           weeklyIncoming,
//           weeklyOutgoing,
//           dailyIncoming,
//           dailyOutgoing,
//           lastUpdated: now,
//         };
//       } catch (error) {
//         console.error(
//           "Error fetching record officer data from SharePoint:",
//           error
//         );
//         // Return mock data to ensure charts are visible
//         return {
//           totalIncoming: 81,
//           totalOutgoing: 1466,
//           monthlyIncoming: 7,
//           monthlyOutgoing: 15,
//           weeklyIncoming: 3,
//           weeklyOutgoing: 5,
//           dailyIncoming: 2,
//           dailyOutgoing: 1,
//           lastUpdated: now,
//         };
//       }
//     } catch (error) {
//       console.error("Error in fetchRecordOfficerStats:", error);
//       throw error;
//     }
//   }
// );

// const dashboardSlice = createSlice({
//   name: "dashboard",
//   initialState,
//   reducers: {
//     // Add a reducer to refresh data on demand
//     refreshDashboards: (state) => {
//       // Reset last updated times to force refresh
//       state.lastUpdated = 0;
//       state.recordOfficerLastUpdated = 0;
//     },
//   },
//   extraReducers: (builder) => {
//     builder
//       // User Dashboard cases
//       .addCase(fetchDashboardStats.pending, (state) => {
//         state.userDashboardStatus = "loading";
//       })
//       .addCase(fetchDashboardStats.fulfilled, (state, action) => {
//         // Skip updating if we're using cached data
//         if (!action.payload) return;

//         state.totalOutgoing = action.payload.totalOutgoing;
//         state.totalIncoming = action.payload.totalIncoming;
//         state.internalIncoming = action.payload.internalIncoming;
//         state.externalIncoming = action.payload.externalIncoming;
//         state.totalCC = action.payload.totalCC;
//         state.outgoingStats = action.payload.outgoingStats;
//         state.incomingStats = action.payload.incomingStats;
//         state.approvalStats = action.payload.approvalStats;
//         state.lastUpdated = action.payload.lastUpdated;
//         state.userDashboardStatus = "succeeded";
//       })
//       .addCase(fetchDashboardStats.rejected, (state) => {
//         state.userDashboardStatus = "failed";
//       })

//       // Record Officer Dashboard cases
//       .addCase(fetchRecordOfficerStats.pending, (state) => {
//         state.recordOfficerLoading = true;
//         state.recordOfficerError = null;
//       })
//       .addCase(fetchRecordOfficerStats.fulfilled, (state, action) => {
//         // Skip updating if we're using cached data
//         if (!action.payload) return;

//         state.recordOfficerLoading = false;
//         state.recordSummary = action.payload;
//         state.recordOfficerLastUpdated = action.payload.lastUpdated;
//       })
//       .addCase(fetchRecordOfficerStats.rejected, (state, action) => {
//         state.recordOfficerLoading = false;
//         state.recordOfficerError =
//           action.error.message || "Failed to fetch stats";
//       });
//   },
// });

// // Export actions
// export const { refreshDashboards } = dashboardSlice.actions;

// // Export selectors
// export const dashboardSelector = (state: RootState) => state.dashboard;
// export const recordOfficerSelector = (state: RootState) => ({
//   recordSummary: state.dashboard.recordSummary,
//   loading: state.dashboard.recordOfficerLoading,
//   error: state.dashboard.recordOfficerError,
// });

// export default dashboardSlice.reducer;
