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

export interface HospitalContact {
    id: number;
    name: string;
    position: string;
    department: string;
    phone_number: string;
    email: string;
    isPrimary: boolean;
    hospital_id: number;
}

interface HospitalContactState {
    items: HospitalContact[];
    status: 'idle' | 'loading' | 'succeeded' | 'failed';
    error: string | null;
}

const initialState: HospitalContactState = {
    items: [],
    status: 'idle',
    error: null,
};

export const fetchHospitalContacts = createAsyncThunk('hospitalContacts/fetchAll', async (params: any, { rejectWithValue }) => {
    try {
        const response = await api.get('/hospital-contacts', { params });

        return response.data.data;
    } catch (err) {
        return rejectWithValue('Failed to fetch hospitals contacts');
    }
});

export const getHospitalContactById = createAsyncThunk('hospitalContacts/fetchOne', async (id: number, { rejectWithValue }) => {
    try {
        const response = await api.get(`/hospital-contacts/${id}`);
        return response.data;
    } catch (err) {
        return rejectWithValue('Failed to fetch hospital contact');
    }
});

export const addHospitalContact = createAsyncThunk(
    'hospitalContacts/add',
    async (data: Partial<HospitalContact>, { rejectWithValue }) => {
        try {
            const response = await api.post('/hospital-contacts', data);
            return response;
        } catch (err) {
            return rejectWithValue('Failed to add hospital contact');
        }
    },
);

export const updateHospitalContact = createAsyncThunk(
    'hospitalContacts/update',
    async ({ id, data }: { id: number; data: Partial<HospitalContact> }, { rejectWithValue }) => {
        try {
            const response = await api.patch(`/hospital-contacts/${id}`, data);

            return response;
        } catch (err) {
            return rejectWithValue('Failed to update hospital contact');
        }
    },
);

export const deleteHospitalContact = createAsyncThunk('hospitalContacts/delete', async (id: any, { rejectWithValue }) => {
    try {
        const response = await api.delete(`/hospital-contacts/${id}`);
        return response;
    } catch (err) {
        return rejectWithValue('Failed to delete hospital contact');
    }
});

const hospitalContactSlice = createSlice({
    name: 'hospitalContacts',
    initialState,
    reducers: {
        clearHospitalContacts(state) {
            state.items = [];
        },
    },
    extraReducers: (builder) => {
        builder
            .addCase(fetchHospitalContacts.pending, (state) => {
                state.status = 'loading';
            })
            .addCase(fetchHospitalContacts.fulfilled, (state, action: PayloadAction<HospitalContact[]>) => {
                state.status = 'succeeded';
                state.items = action.payload;
            })
            .addCase(fetchHospitalContacts.rejected, (state, action) => {
                state.status = 'failed';
                state.error = action.payload as string;
            })
            .addCase(addHospitalContact.fulfilled, (state, action) => {
                if (action?.payload?.data?.code === 200) {
                    state.status = 'succeeded';
                    toast.success(messages.toasts.success.hospital_contact_added);
                } else if (action?.payload?.data?.code === 400) {
                    toast.error(action?.payload?.data?.message || messages.toasts.error.failed_to_add_hospital_contact);
                } else {
                    toast.error(messages.toasts.error.failed_to_add_hospital_contact);
                }
            })
            .addCase(addHospitalContact.rejected, (_, action) => {
                toast.error(action.payload as string);
            })
            .addCase(updateHospitalContact.fulfilled, (state, action) => {
                if (action?.payload?.data?.code === 200) {
                    state.status = 'succeeded';
                    toast.success(messages.toasts.success.hospital_contact_updated);
                } else if (action?.payload?.data?.code === 400) {
                    toast.error(action?.payload?.data?.message || messages.toasts.error.failed_to_update_hospital_contact);
                } else {
                    toast.error(messages.toasts.error.failed_to_update_hospital_contact);
                }
            })
            .addCase(deleteHospitalContact.fulfilled, (state, action) => {
                if (action?.payload?.data?.code == 200) {
                    toast.success(messages.toasts.success.hospital_contact_deleted);
                } else {
                    toast.error(action?.payload?.data?.message || messages.toasts.error.failed_to_delete_hospital_contact);
                }
            });
    },
});

export const { clearHospitalContacts } = hospitalContactSlice.actions;
export default hospitalContactSlice.reducer;
