// stores/attendance-sheet-store.ts
import { create } from 'zustand';
import axiosInstance from '@/utils/axios';
import { AttendanceSheetList, AttendanceSheetPageFilterParams, AttendanceSheet, CreateAttendanceSheetPayload, Circuit, BatchUpdatePayload, AttendanceSheetDetail } from '@/shared/types/attendance-sheet';
import { absenceEndpoints } from '../endpoints/absence';

type AttendanceSheetStore = {
  loading: boolean;
  error: string | null;
  attendanceSheets: AttendanceSheet[];
  totalElements: number;
  fetchAttendanceSheetsPage: (params?: AttendanceSheetPageFilterParams) => Promise<void>;
  createAttendanceSheet: (payload: CreateAttendanceSheetPayload) => Promise<any[]>;
  toggleAttendanceSheetStatus: (id: string) => Promise<void>;
  updateAttendanceStatusBatch:(payload: BatchUpdatePayload)=>Promise<void>;
  getAttendanceSheetDetails:(id: number, month: number, year: number)=>Promise<AttendanceSheetDetail>;
  printingId: number | null;
  exportingId: number | null;
  exportAttendanceSheetPdf: (id: number, month: number, year: number) => Promise<any>;
  printAttendanceSheetPdf: (id: number, month: number, year: number) => Promise<any>;
  currentSheetDetails: any | null;
  detailsLoading: boolean;
  detailsError: string | null;
};

export const useAttendanceSheetStore = create<AttendanceSheetStore>((set) => ({
  loading: false,
  error: null,
  attendanceSheets: [],
  totalElements: 0,
   currentSheetDetails: null,
  detailsLoading: false,
  detailsError: null,
  printingId: null,
  exportingId: null,
  fetchAttendanceSheetsPage: async (params) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get(absenceEndpoints.absence.attendanceSheet.searchAttendanceSheets, {
        params,
      });

      const { content, totalElements } = response.data as AttendanceSheetList;
      set({
        attendanceSheets: content || [],
        totalElements: totalElements || 0,
        loading: false,
      });
    } catch (error: any) {
      set({
        error: error.message || 'Failed to fetch attendance sheets',
        loading: false,
      });
      throw error;
    }
  },
 createAttendanceSheet: async (payload) => {
  set({ loading: true, error: null });
  try {
    const response = await axiosInstance.post(absenceEndpoints.absence.attendanceSheet.createAttendanceSheet, {
      circuitId: payload.circuitId,
      departmentId: payload.departmentId,
      year: payload.year,
      month: payload.month,
    });
    const routeSheets: any[] = response.data;
    if (routeSheets.length === 0) {
          set({ loading: false });
      throw new Error('Aucune feuille de présence retournée');
    }
         set({ loading: false });
    return routeSheets;
  } catch (error: any) {
    set({
      error: error.message || 'Échec de la création de la feuille de présence',
      loading: false,
    });
    throw error;
  }
},
toggleAttendanceSheetStatus: async (id: string) => {
    set({ loading: true, error: null });
    try {
      await axiosInstance.post(`${absenceEndpoints.absence.attendanceSheet.toggleStatus(id)}`);
        
      set({
        loading: false,
      });
    } catch (error: any) {
      set({
        error: error.message || 'Failed to toggle attendance sheet status',
        loading: false,
      });
      throw error;
    }
  },
 
updateAttendanceStatusBatch: async (payload: BatchUpdatePayload) => {
  try {
    await axiosInstance.put(
      `${absenceEndpoints.absence.attendanceSheet.updateAttendanceStatus(payload.attendanceSheetId)}`,
      payload.changes 
    );
  } catch (error) {
    console.error('Erreur lors de la mise à jour des présences:', error);
    throw error;
  }
},
 getAttendanceSheetDetails: async (id: number, month: number, year: number) => {
    set({ detailsLoading: true, detailsError: null });
    try {
      const response = await axiosInstance.get(
        `/api/absence/attendance-sheet/${id}/details?month=${month}&year=${year}`
      );
      set({ 
        currentSheetDetails: response.data,
        detailsLoading: false 
      });
      return response.data;
    } catch (error) {
      set({ 
        detailsLoading: false 
      });
      throw error;
    }
  },
exportAttendanceSheetPdf: async (id: number, month: number, year: number) => {
  set({ exportingId: id });
    try {
      const response = await axiosInstance.get(
        `${absenceEndpoints.absence.attendanceSheet.exportAttendanceSheetPdf(id)}?month=${month}&year=${year}`,
        {
          responseType: 'blob',
          headers: {
            'Accept': 'application/pdf'
          }
        }
      );
      const blob = new Blob([response.data], { type: 'application/pdf' });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `feuille_presence_${id}_${month}_${year}.pdf`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      return response.data;
    } catch (error) {
      console.error('Erreur lors de l\'export PDF:', error);
      throw error;
    } finally {
      set({ exportingId: null });
    }
  },

  printAttendanceSheetPdf: async (id: number, month: number, year: number) => {
    set({ printingId: id });
    try {
      const response = await axiosInstance.get(
        `${absenceEndpoints.absence.attendanceSheet.exportAttendanceSheetPdf(id)}?month=${month}&year=${year}`,
        {
          responseType: 'blob',
          headers: {
            'Accept': 'application/pdf'
          }
        }
      );
      const blob = new Blob([response.data], { type: 'application/pdf' });
      const url = window.URL.createObjectURL(blob);
      const printWindow = window.open(url, '_blank');
      if (printWindow) {
        printWindow.onload = () => {
          printWindow.print();
          printWindow.onafterprint = () => {
            printWindow.close();
            window.URL.revokeObjectURL(url);
          };
        };
      } else {
        const link = document.createElement('a');
        link.href = url;
        link.target = '_blank';
        link.click();
        window.URL.revokeObjectURL(url);
      }
      return response.data;
    } catch (error) {
      console.error('Erreur lors de l\'impression PDF:', error);
      throw error;
    } finally {
      set({ printingId: null });
    }
  }, 
}));