import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import { zohoProjectsAPI } from '../services/zohoProjectsAPI';
import type {
  ZohoProject,
  ZohoTask,
  ZohoIssue,
  ZohoPhase,
  ZohoProjectsFilters,
  ZohoProjectsState,
  ZohoApiInfo,
} from '../types/ZohoProjectsTypes';

const initialState: ZohoProjectsState = {
  projects: [],
  tasks: [],
  issues: [],
  phases: [],
  loading: {
    projects: false,
    tasks: false,
    issues: false,
    phases: false,
  },
  error: {
    projects: null,
    tasks: null,
    issues: null,
    phases: null,
  },
  pagination: {
    projects: { count: 0, moreRecords: false, page: 1 },
    tasks: { count: 0, moreRecords: false, page: 1 },
    issues: { count: 0, moreRecords: false, page: 1 },
    phases: { count: 0, moreRecords: false, page: 1 },
  },
  lastUpdated: null,
  filters: {},
};

// Fetch all projects
export const fetchZohoProjects = createAsyncThunk(
  'zohoProjects/fetchProjects',
  async (params?: { refresh?: boolean }) => {
    const response = await zohoProjectsAPI.getAllProjects();
    return response.data;
  }
);

// Fetch all project tasks
export const fetchZohoTasks = createAsyncThunk(
  'zohoProjects/fetchTasks',
  async (portalId: string) => {
    const response = await zohoProjectsAPI.getAllProjectTasks(portalId);
    return response.data;
  }
);

// Fetch all project issues
export const fetchZohoIssues = createAsyncThunk(
  'zohoProjects/fetchIssues',
  async (portalId: string) => {
    const response = await zohoProjectsAPI.getAllProjectIssues(portalId);
    return response.data;
  }
);

// Fetch all project phases
export const fetchZohoPhases = createAsyncThunk(
  'zohoProjects/fetchPhases',
  async (portalId: string) => {
    const response = await zohoProjectsAPI.getAllProjectPhases(portalId);
    return response.data;
  }
);

// Fetch all data (projects, tasks, issues, phases)
export const fetchAllZohoProjectsData = createAsyncThunk(
  'zohoProjects/fetchAllData',
  async (params: { refresh?: boolean } = {}, { dispatch }) => {
    // First fetch projects
    const projectsResponse = await dispatch(fetchZohoProjects(params));
    console.log('projectsResponse',projectsResponse)
    
    if (fetchZohoProjects.fulfilled.match(projectsResponse) && projectsResponse.payload) {
      const projects = projectsResponse.payload.data.data;
      // Get portal ID from first project
      if (projects.length > 0) {
        const portalId = projects[0].portal.id;
        // Then fetch tasks, issues, and phases in parallel
        await Promise.all([
          dispatch(fetchZohoTasks(portalId)),
          dispatch(fetchZohoIssues(portalId)),
          dispatch(fetchZohoPhases(portalId)),
        ]);
      }
    }
    
    return projectsResponse.payload || null;
  }
);

const zohoProjectsSlice = createSlice({
  name: 'zohoProjects',
  initialState,
  reducers: {
    setFilters: (state, action: PayloadAction<Partial<ZohoProjectsFilters>>) => {
      state.filters = { ...state.filters, ...action.payload };
    },
    clearError: (state, action: PayloadAction<'projects' | 'tasks' | 'issues' | 'phases'>) => {
      if (action.payload === 'projects') {
        state.error.projects = null;
      } else if (action.payload === 'tasks') {
        state.error.tasks = null;
      } else if (action.payload === 'issues') {
        state.error.issues = null;
      } else {
        state.error.phases = null;
      }
    },
    clearAllErrors: (state) => {
      state.error = { projects: null, tasks: null, issues: null, phases: null };
    },
    resetState: () => initialState,
  },
  extraReducers: (builder) => {
    builder
      // Projects cases
      .addCase(fetchZohoProjects.pending, (state) => {
        state.loading.projects = true;
        state.error.projects = null;
      })
      .addCase(fetchZohoProjects.fulfilled, (state, action) => {
        state.loading.projects = false;
        if (action.payload) {
          state.projects = action.payload.data.data;
          state.pagination.projects = action.payload.data.info;
          state.lastUpdated = new Date().toISOString();
        }
      })
      .addCase(fetchZohoProjects.rejected, (state, action) => {
        state.loading.projects = false;
        state.error.projects = action.error.message || 'Failed to load projects';
      })
      // Tasks cases
      .addCase(fetchZohoTasks.pending, (state) => {
        state.loading.tasks = true;
        state.error.tasks = null;
      })
      .addCase(fetchZohoTasks.fulfilled, (state, action) => {
        state.loading.tasks = false;
        if (action.payload) {
          state.tasks = action.payload.data.data;
          state.pagination.tasks = action.payload.data.info;
          state.lastUpdated = new Date().toISOString();
        }
      })
      .addCase(fetchZohoTasks.rejected, (state, action) => {
        state.loading.tasks = false;
        state.error.tasks = action.error.message || 'Failed to load tasks';
      })
      // Issues cases
      .addCase(fetchZohoIssues.pending, (state) => {
        state.loading.issues = true;
        state.error.issues = null;
      })
      .addCase(fetchZohoIssues.fulfilled, (state, action) => {
        state.loading.issues = false;
        if (action.payload) {
          state.issues = action.payload.data.data;
          state.pagination.issues = action.payload.data.info;
          state.lastUpdated = new Date().toISOString();
        }
      })
      .addCase(fetchZohoIssues.rejected, (state, action) => {
        state.loading.issues = false;
        state.error.issues = action.error.message || 'Failed to load issues';
      })
      // Phases cases
      .addCase(fetchZohoPhases.pending, (state) => {
        state.loading.phases = true;
        state.error.phases = null;
      })
      .addCase(fetchZohoPhases.fulfilled, (state, action) => {
        state.loading.phases = false;
        if (action.payload) {
          state.phases = action.payload.data.data;
          state.pagination.phases = action.payload.data.info;
          state.lastUpdated = new Date().toISOString();
        }
      })
      .addCase(fetchZohoPhases.rejected, (state, action) => {
        state.loading.phases = false;
        state.error.phases = action.error.message || 'Failed to load phases';
      })
      // All data cases
      .addCase(fetchAllZohoProjectsData.pending, (state) => {
        state.loading.projects = true;
        state.loading.tasks = true;
        state.loading.issues = true;
        state.loading.phases = true;
        state.error.projects = null;
        state.error.tasks = null;
        state.error.issues = null;
        state.error.phases = null;
      })
      .addCase(fetchAllZohoProjectsData.fulfilled, (state) => {
        state.loading.projects = false;
        state.loading.tasks = false;
        state.loading.issues = false;
        state.loading.phases = false;
        state.lastUpdated = new Date().toISOString();
      })
      .addCase(fetchAllZohoProjectsData.rejected, (state, action) => {
        state.loading.projects = false;
        state.loading.tasks = false;
        state.loading.issues = false;
        state.loading.phases = false;
        state.error.projects = action.error.message || 'Failed to load data';
      });
  },
});

export const { setFilters, clearError, clearAllErrors, resetState } = zohoProjectsSlice.actions;
export default zohoProjectsSlice;


