import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import api from '@/lib/axios';

export interface FleetManagement {
    id: number;
    registration_number: string;
    vin_number: string;
}

export interface IncidentType {
    id: number;
    name: string;
}

export interface IncidentImage {
    id: number;
    incident_id: number;
    image_url: string;
}

export interface TeamMember {
    id: number;
    profile_photo: string;
    first_name: string;
    last_name: string;
}

export interface Incident {
    id: number;
    fleet_id: number;
    trip_id: number | null;
    driver_id: number;
    issue_title: string;
    comment: string | null;
    created_date: string;
    created_time: string;
    fleet_management: FleetManagement;
    incident_type: IncidentType;
    images: IncidentImage[];
    team_member: TeamMember;
}

export interface CreateIncidentDto {
    fleet_id: number;
    driver_id: number;
    issue_title: string;
    comment?: string;
    incident_type_id: number;
    images?: File[];
}

export interface UpdateIncidentDto extends Partial<CreateIncidentDto> {
    id: number;
}

export interface IncidentResponse {
    data: Incident[];
    count: number;
}

export interface IncidentFilters {
    skip?: number;
    limit?: number;
    type?: string;
    driver_id?: string;
    search?: string;
}

interface IncidentReportingState {
    items: Incident[];
    totalCount: number;
    status: 'idle' | 'loading' | 'succeeded' | 'failed';
    error: string | null;
    filters: IncidentFilters;
    incidentTypes: IncidentType[];
    incidentTypesStatus: 'idle' | 'loading' | 'succeeded' | 'failed';
    incidentTypesError: string | null;
}

const initialState: IncidentReportingState = {
    items: [],
    totalCount: 0,
    status: 'idle',
    error: null,
    filters: {
        search: '',
        type: undefined,
        driver_id: undefined,
        limit: 10,
        skip: 0,
    },
    incidentTypes: [],
    incidentTypesStatus: 'idle',
    incidentTypesError: null,
};

export const fetchIncidents = createAsyncThunk(
    'incidentReporting/fetch',
    async (params: IncidentFilters, { rejectWithValue }) => {
        try {
            const response = await api.get('/incident-reporting', { params });
            return response.data.data;
        } catch (err) {
            return rejectWithValue('Failed to fetch incidents');
        }
    },
);

export const fetchIncidentTypes = createAsyncThunk('incidentReporting/fetchTypes', async (_, { rejectWithValue }) => {
    try {
        const response = await api.get('/incident-reporting/incident/types');
        return response.data.data;
    } catch (err) {
        return rejectWithValue('Failed to fetch incident types');
    }
});

const incidentReportingSlice = createSlice({
    name: 'incidentReporting',
    initialState,
    reducers: {
        setFilters(state, action: PayloadAction<Partial<IncidentReportingState['filters']>>) {
            state.filters = { ...state.filters, ...action.payload };
        },
        resetFilters(state) {
            state.filters = initialState.filters;
        },
        setIncidentTypes(state, action: PayloadAction<IncidentType[]>) {
            state.incidentTypes = action.payload;
        },
    },
    extraReducers: (builder) => {
        builder
            .addCase(fetchIncidents.pending, (state) => {
                state.status = 'loading';
            })
            .addCase(fetchIncidents.fulfilled, (state, action) => {
                state.status = 'succeeded';
                state.items = action.payload.data;
                state.totalCount = action.payload.count;
            })
            .addCase(fetchIncidents.rejected, (state, action) => {
                state.status = 'failed';
                state.error = action.payload as string;
            })
            .addCase(fetchIncidentTypes.pending, (state) => {
                state.incidentTypesStatus = 'loading';
            })
            .addCase(fetchIncidentTypes.fulfilled, (state, action) => {
                state.incidentTypesStatus = 'succeeded';
                state.incidentTypes = action.payload;
                state.incidentTypesError = null;
            })
            .addCase(fetchIncidentTypes.rejected, (state, action) => {
                state.incidentTypesStatus = 'failed';
                state.incidentTypesError = action.payload as string;
            });
    },
});

export const { setFilters, resetFilters, setIncidentTypes } = incidentReportingSlice.actions;
export default incidentReportingSlice.reducer;
