import { create } from 'zustand';
import axiosInstance from '@/utils/axios';
import { CollaboratorExportFilterRequest, CollaboratorStatus, IAgent, UserStatus } from '@/shared/types/client';
import { userEndpoints } from '../endpoints/user';

type SearchCollaboratorsParams = {
  firstName?: string;
  lastName?: string;
  email?: string;
  phoneNumber?: string;
  address?: string;
  status?: CollaboratorStatus;
  role?: string;
  page?: number;
  size?: number;
  sortBy?: string;
  sortDirection?: 'asc' | 'desc';
};

export interface ICollaboratorPageable {
  content: IAgent[];
  totalElements: number;
  totalPages: number;
  number: number;
  size: number;
}

type CollaboratorStore = {
  collaborator: IAgent | null;
  collaborators: ICollaboratorPageable | null;
  loading: boolean;
  error: string | null;

  addCollaborator: (data: IAgent) => Promise<void>;
  updateCollaborator: (data: IAgent) => Promise<void>;
  toggleActiveStatus: (id: number | string) => Promise<void>;
  searchCollaborators: (params?: SearchCollaboratorsParams) => Promise<void>;
  changeStatus: (id: string | number, status: CollaboratorStatus) => Promise<void>;
  exportCollaborators: (
    filters: CollaboratorExportFilterRequest
  ) => Promise<string | null>;
  downloadExportFile: (filePath: string) => Promise<Blob | null>;
};

export const useCollaboratorStore = create<CollaboratorStore>((set) => ({
  collaborator: null,
  collaborators: null,
  loading: false,
  error: null,

  addCollaborator: async (data) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.post<IAgent>(
        userEndpoints.user.collaborator.add,
        data
      );
      const created = response.data;
      set((state) => ({
        collaborator: created,
        collaborators: state.collaborators
          ? {
            ...state.collaborators,
            content: [created, ...state.collaborators.content],
          }
          : null,
        loading: false,
        error: null,
      }));
    } catch (error: any) {
      set({ error: error.message || 'Erreur lors de l’ajout', loading: false });
    }
  },

  updateCollaborator: async (data) => {
    set({ loading: true});
    try {
      const response = await axiosInstance.put<IAgent>(
        userEndpoints.user.collaborator.update,
        data
      );
      const updated = response.data;
      set((state) => ({
        collaborator: updated,
        collaborators: state.collaborators
          ? {
            ...state.collaborators,
            content: state.collaborators.content.map((c) => (c.id === updated.id ? updated : c)),
          }
          : null,
        loading: false,
        error: null,
      }));
    } catch (error: any) {
      set({ error: error.message || 'Erreur lors de la mise à jour', loading: false });
    }
  },

  toggleActiveStatus: async (id) => {
    set({ loading: true, error: null });
    try {
      await axiosInstance.post(userEndpoints.user.collaborator.toggleActive(id));
      set((state) => ({
        collaborators: state.collaborators
          ? {
            ...state.collaborators,
            content: state.collaborators.content.map((col) =>
              col.id === id
                ? {
                  ...col,
                  userStatus:
                    col.userStatus === UserStatus.ACTIF ? UserStatus.INACTIF : UserStatus.ACTIF,
                }
                : col
            ),
          }
          : null,
        loading: false,
      }));
    } catch (error: any) {
      set({ error: error.message || 'Erreur lors du changement de statut', loading: false });
    }
  },

  searchCollaborators: async (params = {}) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get<ICollaboratorPageable>(
        userEndpoints.user.collaborator.search,
        { params }
      );
      set({ collaborators: response.data,error: null, loading: false });
    } catch (error: any) {
      set({ error: error.message || 'Erreur lors de la recherche', loading: false });
    }
  },
  changeStatus: async (id, status) => {
    set({ loading: true, error: null });
    try {
      await axiosInstance.get(userEndpoints.user.collaborator.changeStatus(id, status));
      set((state) => ({
        collaborators: state.collaborators
          ? {
            ...state.collaborators,
            content: state.collaborators.content.map((col) =>
              col.id === id ? { ...col, collaboratorStatus: status } : col
            ),
          }
          : null,
        loading: false,
      }));
    } catch (error: any) {
      set({ error: error.message || 'Erreur lors du changement de statut', loading: false });
    }
  },

  exportCollaborators: async (params) => {
    set({ loading: true, error: null });
    try {
      const userId = localStorage.getItem('userId');
      if (userId) {
        const response = await axiosInstance.post(
          userEndpoints.user.collaborator.exportFiltered,
          null,
          { params: { ...params, userId } }
        );
        set({ loading: false });
        return response.data.ExportPath;
      }
      set({ loading: false, error: "Utilisateur non connecté" });
      return null;
    } catch (error: any) {
      set({ error: error.message || "Erreur lors de l’exportation", loading: false });
      return null;
    }
  },

  downloadExportFile: async (filePath) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get<Blob>(
        userEndpoints.user.collaborator.downloadExport(filePath),
        { responseType: 'blob' }
      );
      set({ loading: false });
      return response.data;
    } catch (error: any) {
      set({ error: error.message || "Erreur lors du téléchargement", loading: false });
      return null;
    }
  },
}));
