import { AxiosResponse } from 'axios';
import axiosInstance from '@/utils/axios';
import { IRHAbsence } from '@/shared/types/absence-rh';

const BASE_URL = '/api/absence/rh-absences/calendar';

// Calendar specific interfaces
export interface RhAbsenceCalendarDto {
  id: string;
  absenceNumber?: string;
  userId: number;
  userName?: string;
  firstName: string;
  lastName: string;
  departmentName?: string;
  functionType?: string;
  requestType?: string;
  absenceType?: string;
  leaveType?: string;
  status: string;
  state: string;
  startDate: string;
  endDate: string;
  numberOfDays?: number;
  hoursCount?: number;
  authorizedBy?: string;
  validatedBy?: string;
  receivingMethod?: string;
  affectedToTrip?: boolean;
  observations?: string;
  rhComment?: string;
  displayName?: string;
  statusColor?: string;
  backgroundColor?: string;
}

export interface CalendarStatisticsDto {
  statusCounts: Record<string, number>;
  dailyCounts: Record<string, number>;
  totalAbsences: number;
  approvedCount: number;
  rejectedCount: number;
  pendingCount: number;
  inProgressCount: number;
  absencesByType: Record<string, number>;
}

export interface CalendarFilters {
  startDate?: string;
  endDate?: string;
  statuses?: string[];
  userIds?: number[];
  year?: number;
  month?: number;
  date?: string;
}

// Helper function to build query string for arrays
const buildQueryString = (params: Record<string, any>): string => {
  const queryParts: string[] = [];

  Object.entries(params).forEach(([key, value]) => {
    if (Array.isArray(value)) {
      // For arrays, repeat the parameter name: ?statuses=VAL1&statuses=VAL2
      value.forEach((item) => {
        queryParts.push(`${encodeURIComponent(key)}=${encodeURIComponent(item)}`);
      });
    } else if (value !== undefined && value !== null) {
      queryParts.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
    }
  });

  return queryParts.length > 0 ? `?${queryParts.join('&')}` : '';
};

export const calendarRhAbsenceEndpoints = {
  // Get absences for calendar view (date range)
  getAbsencesForCalendar: (
    filters: CalendarFilters
  ): Promise<AxiosResponse<RhAbsenceCalendarDto[]>> => {
    const params: Record<string, any> = {};

    if (filters.startDate) params.startDate = filters.startDate;
    if (filters.endDate) params.endDate = filters.endDate;
    if (filters.statuses && filters.statuses.length > 0) {
      params.statuses = filters.statuses;
    }
    if (filters.userIds && filters.userIds.length > 0) {
      params.userIds = filters.userIds;
    }

    const queryString = buildQueryString(params);
    return axiosInstance.get(`${BASE_URL}${queryString}`);
  },

  // Get absences for specific date
  getAbsencesForDate: (
    date: string,
    statuses?: string[]
  ): Promise<AxiosResponse<RhAbsenceCalendarDto[]>> => {
    const params: Record<string, any> = {};

    if (statuses && statuses.length > 0) {
      params.statuses = statuses;
    }

    const queryString = buildQueryString(params);
    return axiosInstance.get(`${BASE_URL}/date/${date}${queryString}`);
  },

  // Get absences for specific month
  getAbsencesForMonth: (
    year: number,
    month: number,
    statuses?: string[]
  ): Promise<AxiosResponse<RhAbsenceCalendarDto[]>> => {
    const params: Record<string, any> = {};

    if (statuses && statuses.length > 0) {
      params.statuses = statuses;
    }

    const queryString = buildQueryString(params);
    return axiosInstance.get(`${BASE_URL}/month/${year}/${month}${queryString}`);
  },

  // Get calendar statistics
  getCalendarStatistics: (
    filters: CalendarFilters
  ): Promise<AxiosResponse<CalendarStatisticsDto>> => {
    const params: Record<string, any> = {};

    if (filters.startDate) params.startDate = filters.startDate;
    if (filters.endDate) params.endDate = filters.endDate;
    if (filters.statuses && filters.statuses.length > 0) {
      params.statuses = filters.statuses;
    }

    const queryString = buildQueryString(params);
    return axiosInstance.get(`${BASE_URL}/statistics${queryString}`);
  },
};
