import { useState, useCallback } from 'react';
import { IRHAbsence } from '@/shared/types/absence-rh';
import {
  calendarRhAbsenceEndpoints,
  RhAbsenceCalendarDto,
  CalendarStatisticsDto,
  CalendarFilters,
} from '@/shared/api/endpoints/hr/absence/calendarRhAbsence';

// Hook for RH Absence Calendar
export const useRhAbsenceCalendar = () => {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Transform backend DTO to frontend interface
  const transformToFrontendAbsence = useCallback((dto: RhAbsenceCalendarDto): IRHAbsence => {
    return {
      id: dto.id,
      absenceNumber: dto.absenceNumber,
      userId: dto.userId,
      user: {
        firstName: dto.firstName,
        lastName: dto.lastName,
        departmentName: dto.departmentName,
        functionType: dto.functionType,
      },
      functionType: dto.functionType,
      absenceType: dto.absenceType,
      leaveType: dto.leaveType,
      requestType: dto.requestType,
      startDate: dto.startDate,
      endDate: dto.endDate,
      numberOfDays: dto.numberOfDays || 0,
      hoursCount: dto.hoursCount,
      state: dto.state,
      authorizedBy: dto.authorizedBy,
      validatedBy: dto.validatedBy,
      receivingMethod: dto.receivingMethod,
      affectedToTrip: dto.affectedToTrip,
      observations: dto.observations,
      rhComment: dto.rhComment,

      // Frontend compatibility fields
      numeroEnregistrement: dto.absenceNumber,
      nomChauffeur: dto.displayName || dto.userName || `${dto.firstName} ${dto.lastName}`,
      typeAbsence: dto.absenceType,
      typeAbsenceLabel: dto.absenceType,
      dateDebut: dto.startDate,
      dateFin: dto.endDate,
      statut: mapBackendStatusToFrontend(dto.status || dto.state),
      justificatif: dto.receivingMethod,
      modeReception: dto.receivingMethod,
      nbrHeures: dto.hoursCount,
      validerPar: dto.validatedBy,
      autorisePar: dto.authorizedBy,
      departement: dto.departmentName,
      type: dto.functionType?.toLowerCase() === 'driver' ? 'chauffeur' : 'sédentaire',
      affecteTrajet: dto.affectedToTrip,
      mode: 'view',
    };
  }, []);

  // Get absences for calendar (month view)
  const getAbsencesForCalendar = useCallback(
    async (
      startDate: string,
      endDate: string,
      statuses?: string[],
      userIds?: number[]
    ): Promise<IRHAbsence[]> => {
      setLoading(true);
      setError(null);

      try {
        const filters: CalendarFilters = {
          startDate,
          endDate,
          statuses,
          userIds,
        };

        const response = await calendarRhAbsenceEndpoints.getAbsencesForCalendar(filters);

        return response.data.map(transformToFrontendAbsence);
      } catch (err: any) {
        const errorMessage = err.response?.data?.message || err.message || 'Unknown error occurred';
        console.error('Hook: Calendar absences API error:', err);
        setError(errorMessage);
        throw err;
      } finally {
        setLoading(false);
      }
    },
    [transformToFrontendAbsence]
  );

  // Get absences for specific date
  const getAbsencesForDate = useCallback(
    async (date: string, statuses?: string[]): Promise<IRHAbsence[]> => {
      setLoading(true);
      setError(null);

      try {
        const response = await calendarRhAbsenceEndpoints.getAbsencesForDate(date, statuses);

        return response.data.map(transformToFrontendAbsence);
      } catch (err: any) {
        const errorMessage = err.response?.data?.message || err.message || 'Unknown error occurred';
        console.error('Hook: Date absences API error:', err);
        setError(errorMessage);
        throw err;
      } finally {
        setLoading(false);
      }
    },
    [transformToFrontendAbsence]
  );

  // Get absences for specific month
  const getAbsencesForMonth = useCallback(
    async (year: number, month: number, statuses?: string[]): Promise<IRHAbsence[]> => {
      setLoading(true);
      setError(null);

      try {
        const response = await calendarRhAbsenceEndpoints.getAbsencesForMonth(
          year,
          month,
          statuses
        );

        return response.data.map(transformToFrontendAbsence);
      } catch (err: any) {
        const errorMessage = err.response?.data?.message || err.message || 'Unknown error occurred';
        console.error('Hook: Month absences API error:', err);
        setError(errorMessage);
        throw err;
      } finally {
        setLoading(false);
      }
    },
    [transformToFrontendAbsence]
  );

  // Get calendar statistics
  const getCalendarStatistics = useCallback(
    async (
      startDate: string,
      endDate: string,
      statuses?: string[]
    ): Promise<CalendarStatisticsDto> => {
      setLoading(true);
      setError(null);

      try {
        const filters: CalendarFilters = {
          startDate,
          endDate,
          statuses,
        };

        const response = await calendarRhAbsenceEndpoints.getCalendarStatistics(filters);

        return response.data;
      } catch (err: any) {
        const errorMessage = err.response?.data?.message || err.message || 'Unknown error occurred';

        setError(errorMessage);
        throw err;
      } finally {
        setLoading(false);
      }
    },
    []
  );

  return {
    loading,
    error,
    getAbsencesForCalendar,
    getAbsencesForDate,
    getAbsencesForMonth,
    getCalendarStatistics,
  };
};

// Map backend status to frontend status
const mapBackendStatusToFrontend = (backendStatus: string): string => {
  switch (backendStatus?.toUpperCase()) {
    case 'VALIDATED':
    case 'APPROVED':
      return 'Validé';
    case 'REJECTED':
      return 'Refusé';
    case 'IN_PROGRESS':
    case 'PENDING':
      return 'En cours';
    case 'UNTREATED':
    case 'NON_TRAITE':
      return 'Non traité';
    default:
      return backendStatus || 'Non traité';
  }
};
