import { createSlice, createAsyncThunk, type PayloadAction } from '@reduxjs/toolkit';
import messages from '../../../messages/en.json';

// Define types for the price configuration
export interface PriceConfiguration {
    id: number;
    paymentPlanId: number;
    entityType: 'vehicle_model' | 'add_on' | 'client_type';
    entityId: number;
    entityName: string; // For display purposes
    priceType: 'intercity' | 'intra_city';
    basePrice: number;
    perKmPrice: number;
    minKm?: number;
    additionalNotes?: string;
}

// Define the state type
interface PriceConfigurationsState {
    items: PriceConfiguration[];
    status: 'idle' | 'loading' | 'succeeded' | 'failed';
    error: string | null;
    filters: {
        entityType: string[];
        priceType: string[];
    };
}

// Initial state
const initialState: PriceConfigurationsState = {
    items: [],
    status: 'idle',
    error: null,
    filters: {
        entityType: [],
        priceType: [],
    },
};

// Sample data for initial development
const samplePriceConfigurations: PriceConfiguration[] = [
    // Standard Plan - Vehicle Models
    {
        id: 1,
        paymentPlanId: 1,
        entityType: 'vehicle_model',
        entityId: 1,
        entityName: 'Toyota Camry',
        priceType: 'intercity',
        basePrice: 500,
        perKmPrice: 12,
        minKm: 10,
    },
    {
        id: 2,
        paymentPlanId: 1,
        entityType: 'vehicle_model',
        entityId: 1,
        entityName: 'Toyota Camry',
        priceType: 'intra_city',
        basePrice: 300,
        perKmPrice: 10,
        minKm: 5,
    },
    {
        id: 3,
        paymentPlanId: 1,
        entityType: 'vehicle_model',
        entityId: 7,
        entityName: 'BMW X5',
        priceType: 'intercity',
        basePrice: 1000,
        perKmPrice: 20,
        minKm: 10,
    },
    {
        id: 4,
        paymentPlanId: 1,
        entityType: 'vehicle_model',
        entityId: 7,
        entityName: 'BMW X5',
        priceType: 'intra_city',
        basePrice: 800,
        perKmPrice: 18,
        minKm: 5,
    },

    // Standard Plan - Add-Ons
    {
        id: 5,
        paymentPlanId: 1,
        entityType: 'add_on',
        entityId: 1,
        entityName: 'Wheelchair Access',
        priceType: 'intercity',
        basePrice: 200,
        perKmPrice: 0,
    },
    {
        id: 6,
        paymentPlanId: 1,
        entityType: 'add_on',
        entityId: 1,
        entityName: 'Wheelchair Access',
        priceType: 'intra_city',
        basePrice: 150,
        perKmPrice: 0,
    },

    // Standard Plan - Client Types
    {
        id: 7,
        paymentPlanId: 1,
        entityType: 'client_type',
        entityId: 3,
        entityName: 'Corporate',
        priceType: 'intercity',
        basePrice: 0,
        perKmPrice: 10,
        additionalNotes: '10% discount on base fare',
    },
    {
        id: 8,
        paymentPlanId: 1,
        entityType: 'client_type',
        entityId: 3,
        entityName: 'Corporate',
        priceType: 'intra_city',
        basePrice: 0,
        perKmPrice: 8,
        additionalNotes: '10% discount on base fare',
    },

    // Corporate Plan - Vehicle Models
    {
        id: 9,
        paymentPlanId: 2,
        entityType: 'vehicle_model',
        entityId: 1,
        entityName: 'Toyota Camry',
        priceType: 'intercity',
        basePrice: 450,
        perKmPrice: 10,
        minKm: 10,
    },
    {
        id: 10,
        paymentPlanId: 2,
        entityType: 'vehicle_model',
        entityId: 1,
        entityName: 'Toyota Camry',
        priceType: 'intra_city',
        basePrice: 250,
        perKmPrice: 8,
        minKm: 5,
    },
];

// Define the payload type for adding a new price configuration
export interface AddPriceConfigurationPayload {
    paymentPlanId: number;
    entityType: 'vehicle_model' | 'add_on' | 'client_type';
    entityId: number;
    entityName: string;
    priceType: 'intercity' | 'intra_city';
    basePrice: number;
    perKmPrice: number;
    minKm?: number;
    additionalNotes?: string;
}

// Async thunks for API calls
export const fetchPriceConfigurations = createAsyncThunk(
    'priceConfigurations/fetchPriceConfigurations',
    async (paymentPlanId: number, { rejectWithValue }) => {
        try {
            // In a real app, this would be an API call
            await new Promise((resolve) => setTimeout(resolve, 1000));
            // Filter configurations for the selected payment plan
            return samplePriceConfigurations.filter((config) => config.paymentPlanId === paymentPlanId);
        } catch (error) {
            return rejectWithValue(messages.toasts.error.failed_to_fetch_price_configurations);
        }
    },
);

export const addPriceConfiguration = createAsyncThunk(
    'priceConfigurations/addPriceConfiguration',
    async (payload: AddPriceConfigurationPayload, { rejectWithValue }) => {
        try {
            // In a real app, this would be an API call
            await new Promise((resolve) => setTimeout(resolve, 1000));

            // Generate a new ID (in a real app, the server would do this)
            return {
                id: Date.now(),
                ...payload,
            };
        } catch (error) {
            return rejectWithValue(messages.toasts.error.failed_to_add_price_configuration);
        }
    },
);

export const updatePriceConfiguration = createAsyncThunk(
    'priceConfigurations/updatePriceConfiguration',
    async (payload: { id: number; updates: Partial<PriceConfiguration> }, { rejectWithValue }) => {
        try {
            // In a real app, this would be an API call
            await new Promise((resolve) => setTimeout(resolve, 1000));
            return payload;
        } catch (error) {
            return rejectWithValue(messages.toasts.error.failed_to_update_price_configuration);
        }
    },
);

export const deletePriceConfiguration = createAsyncThunk(
    'priceConfigurations/deletePriceConfiguration',
    async (id: number, { rejectWithValue }) => {
        try {
            // In a real app, this would be an API call
            await new Promise((resolve) => setTimeout(resolve, 1000));
            return id;
        } catch (error) {
            return rejectWithValue(messages.toasts.error.failed_to_delete_price_configuration);
        }
    },
);

// Create the slice
const priceConfigurationsSlice = createSlice({
    name: 'priceConfigurations',
    initialState,
    reducers: {
        updateFilters: (state, action: PayloadAction<Partial<PriceConfigurationsState['filters']>>) => {
            state.filters = { ...state.filters, ...action.payload };
        },
        resetFilters: (state) => {
            state.filters = initialState.filters;
        },
    },
    extraReducers: (builder) => {
        builder
            .addCase(fetchPriceConfigurations.pending, (state) => {
                state.status = 'loading';
            })
            .addCase(fetchPriceConfigurations.fulfilled, (state, action) => {
                state.status = 'succeeded';
                state.items = action.payload;
            })
            .addCase(fetchPriceConfigurations.rejected, (state, action) => {
                state.status = 'failed';
                state.error = action.payload as string;
            })
            .addCase(addPriceConfiguration.fulfilled, (state, action) => {
                state.items.push(action.payload);
            })
            .addCase(updatePriceConfiguration.fulfilled, (state, action) => {
                const { id, updates } = action.payload;
                state.items = state.items.map((item) => (item.id === id ? { ...item, ...updates } : item));
            })
            .addCase(deletePriceConfiguration.fulfilled, (state, action) => {
                state.items = state.items.filter((item) => item.id !== action.payload);
            });
    },
});

export const { updateFilters, resetFilters } = priceConfigurationsSlice.actions;

export default priceConfigurationsSlice.reducer;
