import api from '@/lib/axios';
import { createSlice, createAsyncThunk, type PayloadAction } from '@reduxjs/toolkit';
import { toast } from 'sonner';
import messages from '../../../messages/en.json';

// Define a type for the client contact
export interface ClientContact {
    id: number;
    companyId: number;
    companyName: string;
    firstName: string;
    lastName: string;
    position: string;
    email: string;
    countryCode: string;
    phoneNumber: string;
    allowPlatformAccess: boolean;
    avatar: string;
}

// Define the state type
interface ClientContactsState {
    items: ClientContact[];
    count: number;
    status: 'idle' | 'loading' | 'succeeded' | 'failed';
    error: string | null;
    filters: {
        search: string;
        companies: number[];
        positions: string[];
    };
}

// Initial state
const initialState: ClientContactsState = {
    items: [],
    count: 0,
    status: 'idle',
    error: null,
    filters: {
        search: '',
        companies: [],
        positions: [],
    },
};

// Define the payload type for adding a new client contact
export interface AddClientContactPayload {
    companyId: number;
    firstName: string;
    lastName: string;
    position: string;
    email: string;
    countryCode: string;
    phoneNumber: string;
    allowPlatformAccess: boolean;
}

// Async thunks for API calls
export const fetchClientContacts = createAsyncThunk(
    'clientContacts/fetchClientContacts',
    async (params: any, { rejectWithValue }) => {
        try {
            const response = await api.get('/client-company-contacts', { params });
            return response.data;
        } catch (error: any) {
            return rejectWithValue(error?.response?.data?.message || 'Failed to fetch client contacts');
        }
    },
);

export const addClientContact = createAsyncThunk(
    'clientContacts/addClientContact',
    async (payload: AddClientContactPayload, { rejectWithValue }) => {
        try {
            const response = await api.post('/client-company-contacts', payload);
            return response;
        } catch (error: any) {
            return rejectWithValue(error?.response?.data?.message || 'Failed to add client contact');
        }
    },
);

export const updateClientContact = createAsyncThunk(
    'clientContacts/updateClientContact',
    async (payload: { id: number; updates: Partial<ClientContact> }, { rejectWithValue }) => {
        try {
            const response = await api.patch(`/client-company-contacts/${payload.id}`, payload);
            return response;
        } catch (error: any) {
            return rejectWithValue(error?.response?.data?.message || 'Failed to update client contact');
        }
    },
);

export const clientContactDetail = createAsyncThunk(
    'clientContacts/clientContactDetail',
    async (id: number, { rejectWithValue }) => {
        try {
            const response = await api.get(`/client-company-contacts/${id}`);
            return response.data.data;
        } catch (error: any) {
            return rejectWithValue(error?.response?.data?.message || 'Failed to fetch client contact detail');
        }
    },
);

export const deleteClientContact = createAsyncThunk(
    'clientContacts/deleteClientContact',
    async (id: number, { rejectWithValue }) => {
        try {
            const response = await api.delete(`/client-company-contacts/${id}`);
            return response;
        } catch (error: any) {
            return rejectWithValue(error?.response?.data?.message || 'Failed to delete client contact');
        }
    },
);

// Create the slice
const clientContactsSlice = createSlice({
    name: 'clientContacts',
    initialState,
    reducers: {},
    extraReducers: (builder) => {
        builder
            .addCase(fetchClientContacts.pending, (state) => {
                state.status = 'loading';
            })
            .addCase(fetchClientContacts.fulfilled, (state, action) => {
                state.status = 'succeeded';
                state.count = action.payload.data?.count;
                state.items = action.payload?.data?.data;
            })
            .addCase(fetchClientContacts.rejected, (state, action) => {
                state.status = 'failed';
                state.error = (action.payload as string) || action.error.message || null;
            })
            .addCase(addClientContact.fulfilled, (state, action) => {
                const code = action?.payload?.data?.code;
                if (code === 200) {
                    toast.success(messages.toasts.success.client_contact_added);
                } else if (code === 400 || code === 422) {
                    toast.error(action?.payload?.data?.message || messages.toasts.error.failed_to_add_client_contact);
                } else {
                    toast.error(messages.toasts.error.generic);
                }
            })
            .addCase(updateClientContact.fulfilled, (state, action: any) => {
                const code = action?.payload?.data?.code;

                if (code === 200) {
                    toast.success(messages.toasts.success.client_contact_updated);
                } else if (code === 400 || code === 422) {
                    toast.error(action?.payload?.data?.message || messages.toasts.error.failed_to_update_client_contact);
                } else {
                    toast.error(messages.toasts.error.generic);
                }
            })
            .addCase(deleteClientContact.fulfilled, (state, action) => {
                const code = action?.payload?.data?.code;
                if (code === 200) {
                    toast.success(messages.toasts.success.client_contact_deleted);
                } else if (code === 400) {
                    toast.error(action?.payload?.data?.message || messages.toasts.error.failed_to_delete_client_contact);
                } else {
                    toast.error(messages.toasts.error.generic);
                }
            });
    },
});

export default clientContactsSlice.reducer;
