import { create } from 'zustand';
import axiosInstance from '@/utils/axios';
import { DriverShortResponse, IActiveDriver, IDriverType } from '@/shared/types/driver';
import { driverEndpoints } from '../endpoints/Driver';
import { userEndpoints } from '../endpoints/user';
import { Driver } from '@/shared/sections/chauffeur/planingChauffeur/types';
import { getRuntimeConfig } from '@/services/config';
import { SendingEmailRequest, UserConfirmationRequestOtp, UserPasswordCreationRequest } from '@/shared/types/client';
import { OtpResponseDTO } from '@/shared/types/auth';

interface PageResponse<T> {
  content: T[];
  totalElements: number;
  totalPages: number;
  size: number;
  number: number;
}

export interface DriverFilterParams {
  id?: string;
  firstName?: string;
  lastName?: string;
  email?: string;
  phoneNumber?: string;
  driverStatus?: string;
  residenceCardTitle?: string;
  residencePermitOrIDCard?: string;
  isArchived?: boolean;
  departmentName?: string;
  page?: number;
  size?: number;
  sortBy?: string;
  sortDirection?: string;
}

type DriverStore = {
  drivers: IDriverType[];
  originalDrivers: IDriverType[];
  currentDriver: IDriverType | null;
  totalElements: number;
  totalPages: number;
  loading: boolean;
  error: string | null;
  successMessage: string | null;
  page: number;
  rowsPerPage: number;
  sortBy: string;
  sortDirection: string;

  fetchDrivers: (params?: DriverFilterParams) => Promise<void>;
  fetchDriverDetails: (id: string | number) => Promise<IDriverType | null>;
  setPage: (page: number) => void;
  setRowsPerPage: (rowsPerPage: number) => void;
  setSorting: (sortBy: string, sortDirection: string) => void;
  resetError: () => void;
  createDriver: (driver: Partial<IDriverType>) => Promise<boolean>;
  updateDriver: (id: string, driver: Partial<IDriverType>) => Promise<boolean>;
  toggleActiveDriver: (id: string) => Promise<boolean>;
  exportDrivers: (params: DriverFilterParams & { userId: number }) => Promise<string | null>;
  getActiveDrivers: () => Promise<IActiveDriver[]>;
  getPlanningDrivers: () => Promise<Driver[]>;
  autocompleteDrivers: (keyword?: string) => Promise<{ id: number; firstName: string; lastName: string }[]>;
  getAllDriverShort: () => Promise<DriverShortResponse[]>;
  getAllShorts: () => Promise<DriverShortResponse[]>;
  getDriverDepatmentName : (id: string |number)=> Promise<string | null>;
  // Forgot password methods
  sendResetPassword: (data: SendingEmailRequest) => Promise<any>;
  confirmOtp: (data: UserConfirmationRequestOtp) => Promise<boolean>;
  confirmUserPassword: (data: UserPasswordCreationRequest) => Promise<boolean>;
  getOtpByUsername: (username: string) => Promise<OtpResponseDTO | null>;
};

export const useDriverStore = create<DriverStore>((set, get) => ({
  drivers: [],
  originalDrivers: [],
  currentDriver: null,
  totalElements: 0,
  totalPages: 0,
  loading: false,
  error: null,
  successMessage: null,
  page: 0,
  rowsPerPage: 10,
  sortBy: '',
  sortDirection: 'ASC',

  resetError: () => set({ error: null, successMessage: null }),

  fetchDrivers: async (params) => {
    set({ loading: true, error: null });
    try {
      const { page, rowsPerPage, sortBy, sortDirection } = get();

      const queryParams = {
        ...params,
        page: params?.page ?? page,
        size: params?.size ?? rowsPerPage,
        sortBy: params?.sortBy ?? sortBy,
        sortDirection: params?.sortDirection ?? sortDirection,
      };


      const response = await axiosInstance.get<PageResponse<IDriverType>>(driverEndpoints.search, {
        params: queryParams,
      });



      const { content, totalElements, totalPages } = response.data;

      set({
        drivers: content,
        originalDrivers: content,
        totalElements,
        totalPages,
        loading: false,
        page: queryParams.page,
        rowsPerPage: queryParams.size,
        sortBy: queryParams.sortBy,
        sortDirection: queryParams.sortDirection,
      });
    } catch (error: any) {
      const message =
        error?.response?.data?.message ||
        error?.message ||
        'Failed to fetch drivers';
      set({ error: message, loading: false });
    }
  },

  setPage: (page) => {
    set({ page });
    get().fetchDrivers({ page });
  },

  setRowsPerPage: (rowsPerPage) => {
    set({ rowsPerPage, page: 0 });
    get().fetchDrivers({ size: rowsPerPage, page: 0 });
  },

  setSorting: (sortBy, sortDirection) => {
    set({ sortBy, sortDirection });
    get().fetchDrivers({ sortBy, sortDirection });
  },

  createDriver: async (driver) => {
    set({ loading: true, error: null, successMessage: null });
    try {
      await axiosInstance.post(driverEndpoints.create, driver);
      await get().fetchDrivers();
      set({ loading: false, successMessage: 'Driver created successfully' });
      return true;
    } catch (error: any) {
      const message =
        error?.response?.data?.message ||
        error?.message ||
        'Failed to create driver';
      set({ error: message, loading: false });
      return false;
    }
  },

  updateDriver: async (id, driver) => {
    set({ loading: true, error: null, successMessage: null });
    try {
      console.log('Updating driver:', { id, driver });

      const response = await axiosInstance.put(driverEndpoints.update(id), driver);

      console.log('Update response:', response.data);

      await get().fetchDrivers();

      set({
        loading: false,
        successMessage: 'Driver updated successfully',
        currentDriver: response.data
      });

      return true;
    } catch (error: any) {
      console.error('Driver update error:', {
        message: error.message,
        response: error.response?.data,
        status: error.response?.status
      });

      const message =
        error?.response?.data?.message ||
        error?.message ||
        'Failed to update driver';

      set({
        error: message,
        loading: false,
        successMessage: null
      });

      return false;
    }
  },

  toggleActiveDriver: async (id) => {
    set({ loading: true, error: null, successMessage: null });
    try {
      const response = await axiosInstance.post(driverEndpoints.toggleActive(id));
      await get().fetchDrivers();
      set({ loading: false, successMessage: 'Driver status toggled' });
      return response.data;
    } catch (error: any) {
      const message =
        error?.response?.data?.message ||
        error?.message ||
        'Failed to toggle driver status';
      set({ error: message, loading: false });
      return false;
    }
  },

  fetchDriverDetails: async (id) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get<IDriverType>(driverEndpoints.details(id));
      const driverDetails = response.data;
      set({
        currentDriver: driverDetails,
        loading: false
      });
      return driverDetails;
    } catch (error: any) {
      const message =
        error?.response?.data?.message ||
        error?.message ||
        'Failed to fetch driver details';
      set({ error: message, loading: false, currentDriver: null });
      return null;
    }
  },

  exportDrivers: async (params) => {
    set({ loading: true, error: null });
    try {
      const userId = localStorage.getItem('userId');

      const response = await axiosInstance.post<{ ExportPath: string }>(
        driverEndpoints.export,
        null,
        {
          params: {
            ...params,
            userId: userId
          }
        }
      );

      return response.data.ExportPath;
    } catch (error: any) {
      const message =
        error?.response?.data?.message ||
        error?.message ||
        'Échec de l\'export des chauffeurs';
      set({ error: message, loading: false });
      return null;
    } finally {
      set({ loading: false });
    }
  },
  getActiveDrivers: async () => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get<IActiveDriver[]>(driverEndpoints.active);
      return response.data;
    } catch (error: any) {
      const message =
        error?.response?.data?.message ||
        error?.message ||
        'Failed to fetch active drivers';
      set({ error: message, loading: false });
      return [];
    } finally {
      set({ loading: false });
    }
  },
 getPlanningDrivers : async (): Promise<Driver[]> => {
  set({ loading: true, error: null });
  try {
    
    const config = await getRuntimeConfig();
    console.log("config",config)
    axiosInstance.defaults.baseURL = config.vsnGatewayApiUrl;

    const response = await axiosInstance.get<Driver[]>(driverEndpoints.planning);
    return response.data;
  } catch (error: any) {
    const message =
      error?.response?.data?.message ||
      error?.message ||
      'Failed to fetch planning drivers';
    set({ error: message });
    return [];
  } finally {
    set({ loading: false });
  }
} ,
  autocompleteDrivers: async (keyword?: string) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get<{ id: number; firstName: string; lastName: string }[]>(driverEndpoints.autocomplete, {
        params: { keyword }
      });
      return response.data;
    } catch (error: any) {
      const message =
        error?.response?.data?.message ||
        error?.message ||
        'Failed to autocomplete drivers';
      set({ error: message, loading: false });
      return [];
    } finally {
      set({ loading: false });
    }
  },

  getAllDriverShort: async (): Promise<DriverShortResponse[]> => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get<DriverShortResponse[]>(driverEndpoints.allDrivers);
      set({ loading: false });
      return response.data;
    } catch (error: any) {
      const message =
        error?.response?.data?.message ||
        error?.message ||
        'Failed to fetch driver list';
      set({ error: message, loading: false });
      throw new Error(message);
    }
  },

  getAllShorts: async (): Promise<DriverShortResponse[]> => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get<DriverShortResponse[]>(driverEndpoints.allShorts);
      set({ loading: false });
      return response.data;
    } catch (error: any) {
      const message =
        error?.response?.data?.message ||
        error?.message ||
        'Failed to fetch driver list';
      set({ error: message, loading: false });
      throw new Error(message);
    }
  },
  getDriverDepatmentName: async (id: string | number): Promise<string | null > => {
  set({ loading: true, error: null });
  try {
    const response = await axiosInstance.get<string>(driverEndpoints.departmentName(id));
    const departmentName = response.data;

    set({ loading: false });
    return departmentName;
  } catch (error: any) {
    const message =
      error?.response?.data?.message ||
      error?.message ||
      'Failed to fetch driver department name';

    set({ error: message, loading: false });
    return null;
  }
},

  // Forgot password methods - using collaborator endpoints
  sendResetPassword: async (data) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.post(userEndpoints.user.collaborator.sendResetPassword, data);
      set({ loading: false, error: null });
      return response.data; 
    } catch (error: any) {
      set({ error: error.message || 'Erreur lors de l\'envoi de l\'email de réinitialisation', loading: false });
      return null;
    }
  },

  confirmOtp: async (data) => {
    set({ loading: true, error: null });
    try {
      const isValid = await axiosInstance.post(userEndpoints.user.collaborator.confirmOtp, data);
      set({ loading: false, error: null });
      return isValid.data; 
    } catch (error: any) {
      set({ error: error.message || 'Erreur lors de la confirmation de l\'OTP', loading: false });
      return false;
    }
  },

  confirmUserPassword: async (data) => {
    set({ loading: true, error: null });
    try {
      const passwordCreated = await axiosInstance.put(userEndpoints.user.collaborator.confirmPassword, data);
      set({ loading: false, error: null });
      return passwordCreated.data; 
    } catch (error: any) {
      set({ error: error.message || 'Erreur lors de la confirmation du mot de passe', loading: false });
      return false;
    }
  },

  getOtpByUsername: async (username) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get<OtpResponseDTO>(
        userEndpoints.user.collaborator.getOtpByUsername(username)
      );
      set({ loading: false, error: null });
      return response.data;
    } catch (error: any) {
      set({ error: error.message || 'Erreur lors de la récupération de l\'OTP', loading: false });
      return null;
    }
  }

}));