import { create } from 'zustand';
import axiosInstance from '@/utils/axios';
import { ICandidature } from '@/shared/types/candidature';
import { sedentaryCandidatureEndpoints } from '../../endpoints/hr/recruitment/sedentaryCandidature';

interface SedentaryCandidatureState {
  candidatures: ICandidature[];
  selectedCandidature: ICandidature | null;
  isLoading: boolean;
  error: string | null;

  fetchAllCandidatures: () => Promise<void>;
  fetchCandidatureById: (id: number) => Promise<void>;
  createCandidature: (candidature: ICandidature) => Promise<void>;
  updateCandidature: (id: number, candidature: ICandidature) => Promise<void>;
  deleteCandidature: (id: number) => Promise<void>;
  exportCandidature: (id: number) => Promise<void>;
}

export const useSedentaryCandidatureStore = create<SedentaryCandidatureState>((set) => ({
  candidatures: [],
  selectedCandidature: null,
  isLoading: false,
  error: null,

  // Fetch all candidatures
  fetchAllCandidatures: async () => {
    set({ isLoading: true, error: null });
    try {
      const response = await axiosInstance.get(sedentaryCandidatureEndpoints.getAllCandidatures);
      set({ candidatures: response.data });
    } catch (error) {
      set({ error: 'Failed to fetch candidatures' });
    } finally {
      set({ isLoading: false });
    }
  },

  
  fetchCandidatureById: async (id: number) => {
    set({ isLoading: true, error: null });
    try {
      const response = await axiosInstance.get(sedentaryCandidatureEndpoints.getCandidatureById(id));
      set({ selectedCandidature: response.data });
    } catch (error) {
      set({ error: 'Failed to fetch candidature' });
    } finally {
      set({ isLoading: false });
    }
  },

  // Create a new candidature
  createCandidature: async (candidature: ICandidature) => {
    set({ isLoading: true, error: null });
    try {
      
      const transformedCandidature = {
        ...candidature,
        id: parseInt(candidature.id), 
        departmentId: parseInt(candidature.departement)
      };
      const response = await axiosInstance.post(sedentaryCandidatureEndpoints.createCandidature, transformedCandidature);
      set((state) => ({ candidatures: [...state.candidatures, response.data] }));
    } catch (error) {
      set({ error: 'Failed to create candidature' });
    } finally {
      set({ isLoading: false });
    }
  },

  // Update an existing candidature
  updateCandidature: async (id: number, candidature: ICandidature) => {
    set({ isLoading: true, error: null });
    try {
      const transformedCandidature = {
        ...candidature,
        id: parseInt(candidature.id),
        departmentId: parseInt(candidature.departement),
      };
      await axiosInstance.put(sedentaryCandidatureEndpoints.updateCandidature(id), transformedCandidature);
      set((state) => ({
        candidatures: state.candidatures.map((c) => (parseInt(c.id) === id ? { ...c, ...candidature } : c)),
      }));
    } catch (error) {
      set({ error: 'Failed to update candidature' });
    } finally {
      set({ isLoading: false });
    }
  },

  // Delete a candidature
  deleteCandidature: async (id: number) => {
    set({ isLoading: true, error: null });
    try {
      await axiosInstance.delete(sedentaryCandidatureEndpoints.deleteCandidature(id));
      set((state) => ({
        candidatures: state.candidatures.filter((candidature) => parseInt(candidature.id) !== id),
      }));
    } catch (error) {
      set({ error: 'Failed to delete candidature' });
    } finally {
      set({ isLoading: false });
    }
  },

  // Export a candidature to PDF
  exportCandidature: async (id: number) => {
    try {
      const response = await axiosInstance.get(sedentaryCandidatureEndpoints.exportCandidature(id), {
        responseType: 'blob', ///file response
      });
      const downloadUrl = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = downloadUrl;
      link.setAttribute('download', `candidature_${id}.pdf`);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    } catch (error) {
      set({ error: 'Failed to export candidature' });
    }
  },
}));
