import { createSlice, PayloadAction, createAsyncThunk } from '@reduxjs/toolkit';
import api from '@/lib/axios';
import { InvoiceSettingsPostPayload, InvoiceSettingsResponse } from '@/lib/types/invoiceSettings';
import messages from '../../../messages/en.json';

interface InvoiceSettingsWithId extends InvoiceSettingsResponse {
    id: number;
}

interface InvoiceSettingsState {
    data: InvoiceSettingsResponse | null;
    id: number | null;
    loading: boolean;
    error: string | null;
    status: 'idle' | 'loading' | 'succeeded' | 'failed';
}

const initialState: InvoiceSettingsState = {
    data: null,
    id: null,
    loading: false,
    error: null,
    status: 'idle',
};

export const updateInvoiceSettings = createAsyncThunk<any, { id: number; payload: InvoiceSettingsPostPayload }>(
    'invoiceSettings/updateInvoiceSettings',
    async ({ id, payload }, { rejectWithValue }) => {
        try {
            const response = await api.patch(`/clients/invoice-settings/${id}`, payload);
            return response;
        } catch (error: any) {
            const message = error?.response?.data?.message || messages.toasts.error.failed_to_update_invoice_settings;
            return rejectWithValue(message);
        }
    },
);

// Create new invoice settings (POST /clients/invoice-settings)
export const createInvoiceSettings = createAsyncThunk<any, InvoiceSettingsPostPayload>(
    'invoiceSettings/createInvoiceSettings',
    async (payload, { rejectWithValue }) => {
        try {
            const response = await api.post('/clients/invoice-settings', payload);
            return response;
        } catch (error: any) {
            const message = error?.response?.data?.message || messages.toasts.error.failed_to_create_invoice_settings;
            return rejectWithValue(message);
        }
    },
);

// Fetch settings by client id (GET /clients/invoice-settings/{id})
export const fetchInvoiceSettingsByClient = createAsyncThunk<any, number>(
    'invoiceSettings/fetchByClient',
    async (clientId, { rejectWithValue }) => {
        try {
            const response = await api.get(`/clients/invoice-setting/${clientId}`);
            return response;
        } catch (error: any) {
            return rejectWithValue(error?.response?.data?.message || messages.toasts.error.failed_to_fetch_invoice_settings);
        }
    },
);

const invoiceSettingsSlice = createSlice({
    name: 'invoiceSettings',
    initialState,
    reducers: {
        resetInvoiceSettings(state) {
            state.data = null;
            state.id = null;
            state.loading = false;
            state.error = null;
            state.status = 'idle';
        },
    },
    extraReducers: (builder) => {
        builder
            .addCase(updateInvoiceSettings.pending, (state) => {
                state.loading = true;
                state.error = null;
                state.status = 'loading';
            })
            .addCase(updateInvoiceSettings.fulfilled, (state, action: PayloadAction<any>) => {
                state.loading = false;
                state.data = {
                    fields: action.payload?.data?.data?.fields,
                    comments: action.payload?.data?.data?.notes || '',
                };
                state.status = 'succeeded';
            })
            .addCase(updateInvoiceSettings.rejected, (state, action) => {
                state.loading = false;
                state.error = (action.payload as string) || 'Unknown error';
                state.status = 'failed';
            })
            .addCase(createInvoiceSettings.pending, (state) => {
                state.loading = true;
                state.error = null;
                state.status = 'loading';
            })
            .addCase(createInvoiceSettings.fulfilled, (state, action: PayloadAction<any>) => {
                state.loading = false;
                state.data = {
                    fields: action.payload?.data?.data?.fields,
                    comments: action.payload?.data?.data?.notes || '',
                    client_tax: action?.payload?.data?.data?.client_tax || 0,
                };
                state.id = action.payload?.data?.data?.id;
                state.status = 'succeeded';
            })
            .addCase(createInvoiceSettings.rejected, (state, action) => {
                state.loading = false;
                state.error = (action.payload as string) || 'Unknown error';
                state.status = 'failed';
            });
        builder
            .addCase(fetchInvoiceSettingsByClient.pending, (state) => {
                state.loading = true;
                state.error = null;
                state.status = 'loading';
            })
            .addCase(fetchInvoiceSettingsByClient.fulfilled, (state, action: PayloadAction<any>) => {
                state.loading = false;
                state.data = {
                    fields: action.payload?.data?.data?.fields,
                    comments: action.payload?.data?.data?.notes || '',
                    client_tax: action?.payload?.data?.data?.client_tax || 0,
                };
                state.id = action.payload?.data?.data?.id;
                state.status = 'succeeded';
            })
            .addCase(fetchInvoiceSettingsByClient.rejected, (state, action) => {
                state.loading = false;
                state.error = (action.payload as string) || 'Unknown error';
                state.status = 'failed';
            });
    },
});

export const { resetInvoiceSettings } = invoiceSettingsSlice.actions;
export default invoiceSettingsSlice.reducer;
