import { RejectedActionPayload, ServerErrorResponse } from '@/interface/Shared';
import {
  EmployeeCertification,
  CreateEmployeeCertificationPayload,
  UpdateEmployeeCertificationPayload,
  DeleteEmployeeCertificationPayload,
} from '@/interface/Training';
import Helpers from '@/utilities/Helpers';
import { createAsyncThunk, createSlice, Draft, PayloadAction } from '@reduxjs/toolkit';
import { message } from 'antd';
import { EmployeeCertificationsActions } from './actionTypes';
import { apiDelete, apiGet, apiPost, apiPut } from '@/services/api/api';
import axios, { AxiosResponse } from 'axios';

interface EmployeeCertificationState {
  employeeCertifications: EmployeeCertification[];
  myCertifications: EmployeeCertification[];
  meta: {
    current_page: number;
    last_page: number;
    per_page: number;
    total: number;
  } | null;
  loading: boolean;
  error: string | null;
}

const initialState: EmployeeCertificationState = {
  employeeCertifications: [],
  myCertifications: [],
  meta: null,
  loading: false,
  error: null,
};

export const fetchEmployeeCertifications = createAsyncThunk(
  EmployeeCertificationsActions.FETCH_EMPLOYEE_CERTIFICATIONS_REQUEST,
  async (params?: {
    certification_id?: string;
    employee_id?: string;
    status?: string;
    mandatory?: boolean;
    expiring?: boolean;
    per_page?: number;
  }) => {
    const queryParams = new URLSearchParams();
    if (params?.certification_id)
      queryParams.append('certification_id', params.certification_id);
    if (params?.employee_id) queryParams.append('employee_id', params.employee_id);
    if (params?.status) queryParams.append('status', params.status);
    if (params?.mandatory !== undefined)
      queryParams.append('mandatory', String(params.mandatory));
    if (params?.expiring !== undefined)
      queryParams.append('expiring', String(params.expiring));
    if (params?.per_page) queryParams.append('per_page', String(params.per_page));
    const query = queryParams.toString() ? `?${queryParams.toString()}` : '';
    const response = (await apiGet(
      `/training/employee-certifications${query}`,
    )) as AxiosResponse;
    return response.data;
  },
);

export const createEmployeeCertification = createAsyncThunk(
  EmployeeCertificationsActions.CREATE_EMPLOYEE_CERTIFICATION_REQUEST,
  async (payload: CreateEmployeeCertificationPayload, { rejectWithValue }) => {
    try {
      const response = (await apiPost(
        '/training/employee-certifications',
        payload,
      )) as AxiosResponse<{ data: EmployeeCertification }>;
      return response.data.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const updateEmployeeCertification = createAsyncThunk(
  EmployeeCertificationsActions.UPDATE_EMPLOYEE_CERTIFICATION_REQUEST,
  async (payload: UpdateEmployeeCertificationPayload, { rejectWithValue }) => {
    try {
      const { id, ...data } = payload;
      const response = (await apiPut(
        `/training/employee-certifications/${id}`,
        data,
      )) as AxiosResponse<{ data: EmployeeCertification }>;
      return response.data.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const deleteEmployeeCertification = createAsyncThunk(
  EmployeeCertificationsActions.DELETE_EMPLOYEE_CERTIFICATION_REQUEST,
  async (id: string) => {
    const response = (await apiDelete(
      `/training/employee-certifications/${id}`,
    )) as AxiosResponse<DeleteEmployeeCertificationPayload>;
    const responseData = response.data;
    responseData.id = id;
    return responseData;
  },
);

export const fetchMyCertifications = createAsyncThunk(
  EmployeeCertificationsActions.FETCH_MY_CERTIFICATIONS_REQUEST,
  async () => {
    const response = (await apiGet(
      '/training/employee-certifications/mine',
    )) as AxiosResponse<EmployeeCertification[]>;
    return response.data;
  },
);

export const EmployeeCertificationsSlice = createSlice({
  name: 'employeeCertifications',
  initialState,
  reducers: {},
  extraReducers(builder) {
    builder
      .addCase(
        fetchEmployeeCertifications.pending,
        (state: Draft<EmployeeCertificationState>) => {
          state.loading = true;
          state.error = null;
        },
      )
      .addCase(
        fetchEmployeeCertifications.fulfilled,
        (state: Draft<EmployeeCertificationState>, action: PayloadAction<any>) => {
          if (action.payload?.data && action.payload?.meta) {
            state.employeeCertifications = action.payload.data;
            state.meta = action.payload.meta;
          } else {
            state.employeeCertifications = action.payload;
            state.meta = null;
          }
          state.error = null;
          state.loading = false;
        },
      )
      .addCase(
        fetchEmployeeCertifications.rejected,
        (state: Draft<EmployeeCertificationState>) => {
          state.loading = false;
          state.error =
            'Failed to load employee certifications. Please try again or contact support';
          message.error(
            'Failed to load employee certifications. Please try again or contact support',
          );
        },
      );

    builder
      .addCase(
        createEmployeeCertification.pending,
        (state: Draft<EmployeeCertificationState>) => {
          state.loading = true;
          state.error = null;
        },
      )
      .addCase(
        createEmployeeCertification.fulfilled,
        (
          state: Draft<EmployeeCertificationState>,
          action: PayloadAction<EmployeeCertification>,
        ) => {
          state.employeeCertifications.unshift(action.payload);
          state.error = null;
          state.loading = false;
          message.success('Employee certification created successfully');
        },
      )
      .addCase(
        createEmployeeCertification.rejected,
        (state: Draft<EmployeeCertificationState>, action: RejectedActionPayload) => {
          state.loading = false;
          state.error = Helpers.handleServerError(action.payload);
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(
        updateEmployeeCertification.pending,
        (state: Draft<EmployeeCertificationState>) => {
          state.loading = true;
          state.error = null;
        },
      )
      .addCase(
        updateEmployeeCertification.fulfilled,
        (
          state: Draft<EmployeeCertificationState>,
          action: PayloadAction<EmployeeCertification>,
        ) => {
          const index = state.employeeCertifications.findIndex(
            (ec) => ec.id === action.payload.id,
          );
          if (index !== -1) {
            state.employeeCertifications[index] = action.payload;
          }
          state.loading = false;
          state.error = null;
          message.success('Employee certification updated successfully');
        },
      )
      .addCase(
        updateEmployeeCertification.rejected,
        (state: Draft<EmployeeCertificationState>, action: RejectedActionPayload) => {
          state.loading = false;
          state.error = Helpers.handleServerError(action.payload);
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(
        deleteEmployeeCertification.pending,
        (state: Draft<EmployeeCertificationState>) => {
          state.loading = true;
        },
      )
      .addCase(
        deleteEmployeeCertification.fulfilled,
        (
          state: Draft<EmployeeCertificationState>,
          action: PayloadAction<DeleteEmployeeCertificationPayload>,
        ) => {
          state.employeeCertifications = state.employeeCertifications.filter(
            (ec) => ec.id !== action.payload.id,
          );
          state.loading = false;
          message.success(action.payload.message);
        },
      )
      .addCase(
        deleteEmployeeCertification.rejected,
        (state: Draft<EmployeeCertificationState>) => {
          state.loading = false;
          state.error =
            'Failed to delete employee certification. Please try again or contact support';
          message.error(
            'Failed to delete employee certification. Please try again or contact support',
          );
        },
      );

    builder
      .addCase(
        fetchMyCertifications.pending,
        (state: Draft<EmployeeCertificationState>) => {
          state.loading = true;
          state.error = null;
        },
      )
      .addCase(
        fetchMyCertifications.fulfilled,
        (
          state: Draft<EmployeeCertificationState>,
          action: PayloadAction<EmployeeCertification[]>,
        ) => {
          state.myCertifications = action.payload;
          state.error = null;
          state.loading = false;
        },
      )
      .addCase(
        fetchMyCertifications.rejected,
        (state: Draft<EmployeeCertificationState>) => {
          state.loading = false;
          state.error =
            'Failed to load your certifications. Please try again or contact support';
          message.error(
            'Failed to load your certifications. Please try again or contact support',
          );
        },
      );
  },
});

export default EmployeeCertificationsSlice;
export type { EmployeeCertificationState };
