import { create } from 'zustand';
import axiosInstance from '@/utils/axios';
import { userEndpoints } from '../endpoints/user';
import {
  IEquipe,
  TeamList,
  TeamMinimal,
  TeamRequest,
  TeamStatus,
  mapTeamToRequest,
} from '@/shared/types/equipe';
import { IAgent } from '@/shared/types/client';

type TeamStore = {
  loading: boolean;
  error: string | null;
  teams: TeamList[];
  totalElements: number;
  totalPages: number;
  teamById: IEquipe | null;
  collaboratorsWithoutTeam: IAgent[];
  allCollaborators: IAgent[];
  updateTeam: (team: TeamRequest) => Promise<void>;
  getAllTeams: (params?: TeamPageFilterParams) => Promise<void>;
  createTeam: (team: TeamRequest) => Promise<void>;
  removeMember: (teamId: number, memberId: number) => Promise<void>;
  toggleTeamStatus: (teamId: string) => Promise<void>;
  getTeamById: (id: string) => Promise<IEquipe | null>;
  duplicateTeam: (teamId: string, teamData: TeamRequest) => Promise<void>;
  exportTeams: (params: TeamExportParams) => Promise<string | null>;
  getAllCollaborators: () => Promise<void>;
  minimalTeams: TeamMinimal[];
  getMinimalTeams: () => Promise<void>;
};
type TeamExportParams = {
  id?: string;
  name?: string;
  teamCode?: string;
  status?: TeamStatus;
  creationDateStart?: string;
  creationDateEnd?: string;
  departmentName?: string;
  userId?: number;
};

type TeamPageFilterParams = {
  page?: number;
  size?: number;
  sortBy?: string;
  sortDirection?: 'asc' | 'desc';
  status?: TeamStatus;
};

export const useTeamStore = create<TeamStore>((set) => ({
  loading: false,
  error: null,
  teams: [],
  totalElements: 0,
  totalPages: 0,
  teamById: null,
  collaboratorsWithoutTeam: [],
  allCollaborators: [],

  getAllTeams: async (params = {}) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get(userEndpoints.user.team.getAllTeams, {
        params: {
          page: params.page ?? 0,
          size: params.size ?? 20,
          sortBy: params.sortBy ?? 'id',
          sortDirection: params.sortDirection ?? 'desc',
          ...params,
        },
      });

      const { content, totalElements, totalPages } = response.data;
      set({
        teams: content,
        totalElements,
        totalPages,
        loading: false,
      });
    } catch (error: any) {
      set({
        teams: [],
        totalElements: 0,
        totalPages: 0,
        error: error.message || 'Failed to fetch teams',
        loading: false,
      });
    }
  },

  createTeam: async (team: TeamRequest) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.post(userEndpoints.user.team.createTeam, team);
      set({ loading: false });
      return response.data;
    } catch (error: any) {
      set({
        error: error.message || 'Failed to create team',
        loading: false,
      });
      throw error;
    }
  },

  removeMember: async (teamId: number, memberId: number) => {
    set({ loading: true, error: null });
    try {
      await axiosInstance.delete(userEndpoints.user.team.removeMember(teamId, memberId));
      set({ loading: false });
    } catch (error: any) {
      set({
        error: error.message || 'Failed to remove team member',
        loading: false,
      });
      throw error;
    }
  },

  updateTeam: async (team: TeamRequest) => {
    set({ loading: true, error: null });
    try {
      await axiosInstance.post(`${userEndpoints.user.team.updateTeam}/${team.id}`, team);
      set({ loading: false });
    } catch (error: any) {
      set({
        error: error.message || 'Failed to update team',
        loading: false,
      });
      throw error;
    }
  },

  getTeamById: async (id: string) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get(userEndpoints.user.team.getTeamById(id));

      set({ loading: false, teamById: response.data as IEquipe });
      return response.data as IEquipe;
    } catch (error: any) {
      set({
        error: error.message || 'Failed to fetch team by ID',
        loading: false,
      });
      return null;
    }
  },
  toggleTeamStatus: async (teamId: string) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.post(userEndpoints.user.team.toggleStatus(teamId));
      set((state) => ({
        teams: state.teams.map((team) => 
          team.id === teamId 
            ? { ...team, status: team.status === TeamStatus.ACTIVE ? TeamStatus.INACTIVE : TeamStatus.ACTIVE }
            : team
        ),
        loading: false,
      }));
      return response.data;
    } catch (error: any) {
      set({
        error: error.message || 'Failed to toggle team status',
        loading: false,
      });
      throw error;
    }
  },
duplicateTeam: async (teamId: string, teamData: TeamRequest) => {
  set({ loading: true, error: null });
  try {
    const response = await axiosInstance.post(
      `${userEndpoints.user.team.duplicateTeam}/${teamId}`,
      teamData
    );
    set({ loading: false });
    return response.data;
  } catch (error: any) {
    set({
      error: error.message || 'Failed to duplicate team',
      loading: false,
    });
    throw error;
  }
},
exportTeams: async (params) => {
  set({ loading: true, error: null });
  try {
    const response = await axiosInstance.post<{ ExportPath: string }>(
      userEndpoints.user.team.exportTeams,
      null,
      { 
        params: {
          ...params,
          userId: 1 
        }
      }
    );

      return response.data.ExportPath;
    } catch (error: any) {
      set({
        error: error.message || "Échec de l'export des équipes",
        loading: false,
      });
      return null;
    } finally {
      set({ loading: false });
    }
  },
  getCollaboratorsWithoutTeam: async () => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get('/api/user/collaborators/without-team');
      set({
        collaboratorsWithoutTeam: response.data as IAgent[],
        loading: false,
      });
    } catch (error: any) {
      set({
        collaboratorsWithoutTeam: [],
        error: error.message || 'Failed to fetch collaborators without team',
        loading: false,
      });
    }
  },

  getAllCollaborators: async () => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get('/api/user/collaborators/search');
      set({
        allCollaborators: response.data.content as IAgent[],
        loading: false,
      });
    } catch (error: any) {
      set({
        allCollaborators: [],
        error: error.message || 'Failed to fetch all collaborators',
        loading: false,
      });
    }
  },
  minimalTeams: [],

  getMinimalTeams: async () => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get<TeamMinimal[]>(
        userEndpoints.user.team.findAllTeamIdAndName
      );
      set({
        minimalTeams: response.data,
        loading: false,
      });
    } catch (error: any) {
      set({
        minimalTeams: [],
        error: error.message || 'Failed to fetch minimal teams',
        loading: false,
      });
    }
  }
}));
