import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import { LeadState, Lead, LeadFilters } from '../types/lead';
import { RootState } from './store';
import { sanitizeLeadData } from '../utils/sanitization';

export const fetchLeads = createAsyncThunk<Lead[], void, { rejectValue: string }>(
  'leads/fetchLeads',
  async (_, { rejectWithValue }) => {
    try {
      const response = await fetch('/api/leads', {
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
        credentials: 'include',
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.message || 'Failed to fetch leads');
      }

      const data = await response.json();
      return data.map((lead: Lead) => sanitizeLeadData(lead));
    } catch (error) {
      return rejectWithValue(error instanceof Error ? error.message : 'An unknown error occurred');
    }
  }
);

const initialState: LeadState = {
  leads: [],
  loading: false,
  error: null,
  lastUpdated: undefined,
};

const leadSlice = createSlice({
  name: 'leads',
  initialState,
  reducers: {
    filterLeads: (state, action: PayloadAction<LeadFilters>) => {
      // Implementation for filtering leads
    },
    clearError: (state) => {
      state.error = null;
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchLeads.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchLeads.fulfilled, (state, action) => {
        state.leads = action.payload;
        state.loading = false;
        state.lastUpdated = new Date().toISOString();
      })
      .addCase(fetchLeads.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload || 'Failed to fetch leads';
      });
  },
});

export const { filterLeads, clearError } = leadSlice.actions;

export const selectAllLeads = (state: RootState) => state.leads.leads;
export const selectLeadsLoading = (state: RootState) => state.leads.loading;
export const selectLeadsError = (state: RootState) => state.leads.error;
export const selectLastUpdated = (state: RootState) => state.leads.lastUpdated;

export default leadSlice.reducer;