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';

// Type definitions
export interface InspectionReportFleet {
    id: number;
    registration_number: string;
}

export interface InspectionReportDriver {
    id: number;
    first_name: string;
    last_name: string;
    country_code: string;
    phone_number: string;
    reporting_to?: {
        id: number;
        first_name: string;
        last_name: string;
        country_code: string;
        phone_number: string;
    };
}

export interface InspectionReportOption {
    id: number;
    option_text: string;
    selected: boolean;
}

export interface InspectionReportAnswer {
    question: string;
    selected_answer: string;
    options: InspectionReportOption[];
}

export interface InspectionReport {
    id: number;
    fleet: InspectionReportFleet;
    driver: InspectionReportDriver;
    inspection_answers: InspectionReportAnswer[];
    front_side_photo?: string;
    right_side_photo?: string;
    back_side_photo?: string;
    left_side_photo?: string;
    created_at: string;
}

interface InspectionReportState {
    items: InspectionReport[];
    selectedReport: InspectionReport | null;
    totalCount: number;
    status: 'idle' | 'loading' | 'succeeded' | 'failed';
    detailStatus: 'idle' | 'loading' | 'succeeded' | 'failed';
    error: string | null;
    filters: {
        fleet_id: number;
        limit: number;
        skip: number;
    };
}

const initialState: InspectionReportState = {
    items: [],
    selectedReport: null,
    totalCount: 0,
    status: 'idle',
    detailStatus: 'idle',
    error: null,
    filters: {
        fleet_id: 0,
        limit: 10,
        skip: 0,
    },
};

// Async thunks
export const fetchInspectionReports = createAsyncThunk(
    'inspectionReports/fetch',
    async (params: { fleet_id: number; limit?: number; skip?: number }, { rejectWithValue }) => {
        try {
            const response = await api.get('/inspection-questions/inspection-report', { params });
            return response.data.data;
        } catch (err) {
            return rejectWithValue(messages.toasts.error.failed_to_fetch_inspection_reports);
        }
    },
);

export const fetchInspectionReportById = createAsyncThunk(
    'inspectionReports/fetchById',
    async (id: number, { rejectWithValue }) => {
        try {
            const response = await api.get(`/inspection-questions/inspection-report/${id}`);
            return response.data.data;
        } catch (err) {
            return rejectWithValue(messages.toasts.error.failed_to_fetch_inspection_report_details);
        }
    },
);

// Slice
const inspectionReportSlice = createSlice({
    name: 'inspectionReports',
    initialState,
    reducers: {
        setFilters(state, action: PayloadAction<Partial<InspectionReportState['filters']>>) {
            state.filters = { ...state.filters, ...action.payload };
        },
        resetFilters(state) {
            state.filters = initialState.filters;
        },
        clearReports(state) {
            state.items = [];
            state.totalCount = 0;
        },
        clearSelectedReport(state) {
            state.selectedReport = null;
            state.detailStatus = 'idle';
        },
    },
    extraReducers: (builder) => {
        builder
            .addCase(fetchInspectionReports.pending, (state) => {
                state.status = 'loading';
            })
            .addCase(fetchInspectionReports.fulfilled, (state, action) => {
                state.status = 'succeeded';
                state.items = action.payload.data || [];
                state.totalCount = action.payload.count || 0;
            })
            .addCase(fetchInspectionReports.rejected, (state, action) => {
                state.status = 'failed';
                state.error = action.payload as string;
                toast.error(action.payload as string);
            })
            .addCase(fetchInspectionReportById.pending, (state) => {
                state.detailStatus = 'loading';
            })
            .addCase(fetchInspectionReportById.fulfilled, (state, action) => {
                state.detailStatus = 'succeeded';
                state.selectedReport = action.payload;
            })
            .addCase(fetchInspectionReportById.rejected, (state, action) => {
                state.detailStatus = 'failed';
                toast.error(action.payload as string);
            });
    },
});

export const { setFilters, resetFilters, clearReports, clearSelectedReport } = inspectionReportSlice.actions;
export default inspectionReportSlice.reducer;
