import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import { zohoPeopleAPI } from '../services/zohoPeopleAPI';
import type { 
  ZohoPeopleState, 
  AttendanceReportData, 
  EmployeeFormData, 
  HolidayData, 
  LeaveTrackerReportData, 
  LeaveDataItem 
} from '../types/zohoPeopleTypes';

// Initial state
const initialState: ZohoPeopleState = {
  attendanceReport: null,
  employeeForms: null,
  holidays: null,
  leaveTracker: null,
  leaveData: null,
  loading: false,
  error: null,
  lastUpdated: null,
};

// Async thunks
export const fetchZohoPeopleData = createAsyncThunk(
  'zohoPeople/fetchAllData',
  async () => {
    const response = await zohoPeopleAPI.getAllDashboardData();
    return response;
  }
);

export const fetchAttendanceReport = createAsyncThunk(
  'zohoPeople/fetchAttendanceReport',
  async () => {
    const response = await zohoPeopleAPI.getAttendanceReport();
    return response.data.data;
  }
);

export const fetchEmployeeForms = createAsyncThunk(
  'zohoPeople/fetchEmployeeForms',
  async (params: { page?: number; limit?: number } = {}) => {
    const response = await zohoPeopleAPI.getEmployeeForms(params.page, params.limit);
    return response.data.data.flatMap(emp => Object.values(emp).flat());
  }
);

export const fetchHolidays = createAsyncThunk(
  'zohoPeople/fetchHolidays',
  async () => {
    const response = await zohoPeopleAPI.getHolidays();
    return response.data.data;
  }
);

export const fetchLeaveTrackerReport = createAsyncThunk(
  'zohoPeople/fetchLeaveTrackerReport',
  async () => {
    const response = await zohoPeopleAPI.getLeaveTrackerReport();
    return response.data.data[0];
  }
);

export const fetchLeaveData = createAsyncThunk(
  'zohoPeople/fetchLeaveData',
  async () => {
    const response = await zohoPeopleAPI.getLeaveData();
    return response.data.data.flatMap(leave => Object.values(leave).flat());
  }
);

// Slice
const zohoPeopleSlice = createSlice({
  name: 'zohoPeople',
  initialState,
  reducers: {
    clearError: (state) => {
      state.error = null;
    },
    resetState: () => initialState,
  },
  extraReducers: (builder) => {
    // Fetch all data
    builder
      .addCase(fetchZohoPeopleData.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchZohoPeopleData.fulfilled, (state, action) => {
        state.loading = false;
        state.attendanceReport = action.payload.attendanceReport;
        state.employeeForms = action.payload.employeeForms;
        state.holidays = action.payload.holidays;
        state.leaveTracker = action.payload.leaveTracker;
        state.leaveData = action.payload.leaveData;
        state.lastUpdated = new Date().toISOString();
      })
      .addCase(fetchZohoPeopleData.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message || 'Failed to fetch Zoho People data';
      });

    // Individual data fetchers
    builder
      .addCase(fetchAttendanceReport.fulfilled, (state, action) => {
        state.attendanceReport = action.payload;
        state.lastUpdated = new Date().toISOString();
      })
      .addCase(fetchEmployeeForms.fulfilled, (state, action) => {
        state.employeeForms = action.payload;
        state.lastUpdated = new Date().toISOString();
      })
      .addCase(fetchHolidays.fulfilled, (state, action) => {
        state.holidays = action.payload;
        state.lastUpdated = new Date().toISOString();
      })
      .addCase(fetchLeaveTrackerReport.fulfilled, (state, action) => {
        state.leaveTracker = action.payload;
        state.lastUpdated = new Date().toISOString();
      })
      .addCase(fetchLeaveData.fulfilled, (state, action) => {
        state.leaveData = action.payload;
        state.lastUpdated = new Date().toISOString();
      });
  },
});

export const { clearError, resetState } = zohoPeopleSlice.actions;
export default zohoPeopleSlice;