import { create } from 'zustand';
import { userEndpoints } from '../endpoints/user';
import {
  ClientTypeDTO,
  IClient,
  IClientPageable,
  MainBranch,
  PortalAssignment,
} from '@/shared/types/client';
import { UserStatus } from '@/shared/types/client'; // Assurez-vous que UserStatus est bien importé
import axiosInstance from '@/utils/axios';

type SearchClientsParams = {
  id?: string;
  clientName?: string;
  clientType?: string;
  siret?: string;
  mainBranch?: MainBranch;
  apeCode?: number;
  landlinePhone?: string;
  phoneNumber?: string;
  email?: string;
  observation?: string;
  bankName?: string;
  iban?: string;
  signatureDate?: string;
  colorCode?: string;
  accountingAccount?: string;
  auxiliaryAccount?: string;
  salesAccount?: string;
  paymentDate?: string;
  portalAssignment?: PortalAssignment;
  sortBy?: string;
  sortDirection?: 'asc' | 'desc';
  page?: number;
  size?: number;
};

type ClientStore = {
  client: IClient | null;
  clients: IClientPageable | null;
  clientTypes: ClientTypeDTO[];
  loading: boolean;
  error: string | null;
  addClient: (clientData: IClient) => Promise<void>;
  updateClient: (clientData: IClient) => Promise<void>; // Added updateClient method
  getAllClients: (params?: SearchClientsParams) => Promise<void>;
  getAllClientTypes: () => Promise<void>;
  toggleClientActive: (id: string) => Promise<void>; 
  exportClients: (params: SearchClientsParams & { userId: number }) => Promise<string | null>;
};

export const useClientStore = create<ClientStore>((set) => ({
  client: null,
  clients: null,
  clientTypes: [],
  loading: false,
  error: null,

  addClient: async (clientData) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.post<IClient>(
        userEndpoints.user.client.addClient,
        clientData
      );

      const newClient = response.data;

      set((state) => {
        if (!state.clients || !state.clients.content) {
          return {
            client: newClient,
            loading: false,
          };
        }

        const updatedContent = [
          newClient,
          ...state.clients.content.slice(0, state.clients.content.length - 1),
        ];

        return {
          client: newClient,
          clients: {
            ...state.clients,
            content: updatedContent,
          },
          loading: false,
        } as Partial<ClientStore>;
      });
    } catch (error: any) {
      set({ error: error.message || 'Failed to add client', loading: false });
    }
  },

  updateClient: async (clientData) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.put<IClient>(
        userEndpoints.user.client.updateClient,  
        clientData
      );

      const updatedClient = response.data;

      set((state) => {
        if (!state.clients || !state.clients.content) {
          return {
            client: updatedClient,
            loading: false,
          };
        }

        const updatedContent = state.clients.content.map((client) =>
          client.id === updatedClient.id ? updatedClient : client
        );

        return {
          client: updatedClient,
          clients: {
            ...state.clients,
            content: updatedContent,
          },
          loading: false,
        } as Partial<ClientStore>;
      });
    } catch (error: any) {
      set({ error: error.message || 'Failed to update client', loading: false });
    }
  },

  getAllClients: async (params = {}) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get<IClientPageable>(
        userEndpoints.user.client.getAllClients,
        { params }
      );
      set({ clients: response.data, loading: false });
    } catch (error: any) {
      set({ error: error.message || 'Failed to fetch clients', loading: false });
    }
  },

  getAllClientTypes: async () => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get<ClientTypeDTO[]>(
        userEndpoints.user.clientType.getAll
      );
      set({ clientTypes: response.data, loading: false });
    } catch (error: any) {
      set({ error: error.message || 'Failed to fetch client types', loading: false });
    } finally {
      set({ loading: false });
    }
  },

  toggleClientActive: async (id: string): Promise<void> => {
    set({ loading: true, error: null });
    try {
      await axiosInstance.post<boolean>(userEndpoints.user.client.toggleActiveClient(id));
      set((state) => {
        if (!state.clients) return { loading: false };
        const updatedClients = (state.clients.content || []).map((client) =>
          client.id === id
            ? {
                ...client,
                userStatus:
                  client.userStatus === UserStatus.ACTIF ? UserStatus.INACTIF : UserStatus.ACTIF,
              }
            : client
        );

        return {
          clients: {
            ...state.clients,
            content: updatedClients,
          },
          loading: false,
        };
      });
    } catch (error: any) {
      set({ error: error.message || 'Failed to toggle client active state', loading: false });
    }
  },
  exportClients: async (params) => {
  set({ loading: true, error: null });
  try {
    const response = await axiosInstance.post<{ ExportPath: string }>(
      userEndpoints.user.client.exportClients, // ➜ définis ce endpoint dans tes `userEndpoints`
      null,
      { params }
    );

    return response.data.ExportPath;
  } catch (error: any) {
    set({ error: error.message || 'Échec de l’export des clients', loading: false });
    return null;
  } finally {
    set({ loading: false });
  }
},

}));
