import { create } from 'zustand';
import axiosInstance from '@/utils/axios';
import { IActiveDriver, IDriverType } from '@/shared/types/driver';
import { driverEndpoints } from '../endpoints/Driver';

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[]>;

};

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 response = await axiosInstance.post<{ ExportPath: string }>(
        driverEndpoints.export,
        null,
        { params }
      );

      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 });
  }
},

}));


