import { create } from 'zustand';
import { roadMapEndpoints } from '../endpoints/roadMap';

import axiosInstance from '@/utils/axios';
import { DriverRoadMapDetailsDTO, IRoadmap, IRoadMapStatistics, OldRoadMapByDriverFilterParams, RoadMapPageFilterParams, SubmittedRoadMapDTO, SubmittedRoadMapFilterParams } from '@/shared/types/roadMap';
import { IOldRoadmap, IValidRoadmap, OldSubmittedRoadMapFilterParams, ValidRoadmapFilterParams } from '@/shared/types/driver';


type RoadMapStore = {
  validatedRoadMap: IRoadmap[];
  roadMapStatistics: IRoadMapStatistics | null; 
  dealvalidatedRoadMap: IValidRoadmap[];
  submittedRoadMaps: SubmittedRoadMapDTO[];
  oldSubmittedRoadMaps: IOldRoadmap[];
  loading: boolean;
  error: string | null;
  getAllValidRoadMap: (params?: RoadMapPageFilterParams) => Promise<void>;
  getAllSubmittedRoadMaps: (params?: SubmittedRoadMapFilterParams) => Promise<void>;
  getOldSubmittedRoadMaps: (params: OldSubmittedRoadMapFilterParams) => Promise<void>;
  oldSubmittedRoadMapDetails: DriverRoadMapDetailsDTO | null;
  getOldSubmittedRoadMapDetails: (id: number) => Promise<void>;
  totalElements: number;
  createValidatedRoadMapsManually: (payload: { driverIds: number[]; date: string }) => Promise<void>;
  getOldRoadMapByDriver: (params?: OldRoadMapByDriverFilterParams) => Promise<void>;
  getAllDealValidRoadMap: (params?: ValidRoadmapFilterParams) => Promise<void>;
  getRoadMapStatistics: () => Promise<void>;
  createRoadMapsManually: (payload: { driverIds: number[]; date: string }) => Promise<void>;

};

export const useRoadMapStore = create<RoadMapStore>((set) => ({
  validatedRoadMap: [],
  roadMapStatistics:null,
  dealvalidatedRoadMap: [],
  submittedRoadMaps: [],
  oldSubmittedRoadMaps: [],
  oldSubmittedRoadMapDetails: null,
  loading: false,
  error: null,
  totalElements: 0,


  getAllValidRoadMap: async (params = {status}) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get(
        roadMapEndpoints.roadMap.validaRoadMap.getAllValidRoadmap,
        { params }
      );
      const { content, totalElements } = response.data;
      set({ validatedRoadMap: content, loading: false });
    } catch (error: any) {
      set({ error: error.message || 'Failed to fetch validatedRoadMap', loading: false });
    }
  },

  getAllSubmittedRoadMaps: async (params = {}) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get(
        roadMapEndpoints.roadMap.submittedRoadMap.getAllsubmittedRoadmap,
        { params }
      );
      const { content , totalElements} = response.data;
      set({ submittedRoadMaps: content, loading: false , totalElements });
    } catch (error: any) {
      set({ error: error.message || 'Failed to fetch submittedRoadMaps', loading: false });
    }
  },

  getOldSubmittedRoadMaps: async (params) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get(
        roadMapEndpoints.roadMap.submittedRoadMap.getOldSubmittedRoadmaps,
        { params }
      );
      const { content , totalElements} = response.data;

      const mappedContent: IOldRoadmap[] = content.map((item: any) => ({
        id: String(item.id),
        name: item.name,
        date: item.date,
        nombreHeures: item.totalHours != null ? String(item.totalHours) : '—',
      }));

      set({ oldSubmittedRoadMaps: mappedContent, loading: false , totalElements});
    } catch (error: any) {
      set({ error: error.message || 'Failed to fetch old submitted roadmaps', loading: false });
    }
  },
  createValidatedRoadMapsManually: async (payload: { driverIds: number[]; date: string }) => {
  set({ loading: true, error: null });
  try {
    await axiosInstance.post(
      roadMapEndpoints.roadMap.validaRoadMap.add,
      payload
    );
    set({ loading: false });
  } catch (error: any) {
    set({
      error: error.response?.data?.message || 'Erreur lors de la création des feuilles de route',
      loading: false,
    });
  }
},

  
  getOldSubmittedRoadMapDetails: async (id) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get(
        roadMapEndpoints.roadMap.submittedRoadMap.getOldSubmittedRoadmapDetails(id)
      );
      set({ oldSubmittedRoadMapDetails: response.data, loading: false });
    } catch (error: any) {
      set({ error: error.message || 'Failed to fetch old submitted roadmap details', loading: false });
    }
  },
   getOldRoadMapByDriver: async (params) => {
  if (!params?.driverId) {
    set({ error: 'ID du chauffeur requis', loading: false });
    return;
  }

  set({ loading: true, error: null });
  try {
    const response = await axiosInstance.get(
      roadMapEndpoints.roadMap.validaRoadMap.getOldRoadmapByDriver(params.driverId),
      { params }
    );
    const { content, totalElements } = response.data;
    set({ validatedRoadMap: content, loading: false });
  } catch (error: any) {
    set({ error: error.message || 'Failed to fetch validatedRoadMap', loading: false });
  }
},
  getAllDealValidRoadMap: async (params) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get(
        roadMapEndpoints.roadMap.validaRoadMap.getAllDelaValidRoadmap,
        { params }
      );
      const { content, totalElements } = response.data;
      set({ dealvalidatedRoadMap: content, loading: false });
    } catch (error: any) {
      set({ error: error.message || 'Failed to fetch validatedRoadMap', loading: false });
    }
  },
  getRoadMapStatistics: async () => {
  set({ loading: true, error: null });
  try {
    const response = await axiosInstance.get(
      roadMapEndpoints.roadMap.statistics.getStatistics
    );
    set({ roadMapStatistics: response.data, loading: false });
  } catch (error: any) {
    set({
      error: error.message || 'Erreur lors de la récupération des statistiques',
      loading: false,
    });
  }
},

createRoadMapsManually: async (payload: { driverIds: number[]; date: string }) => {
  set({ loading: true, error: null });
  try {
    await axiosInstance.post(
      roadMapEndpoints.roadMap.submittedRoadMap.create, 
      payload
    );
    set({ loading: false });
  } catch (error: any) {
    set({
      error: error.response?.data?.message || 'Erreur lors de la création manuelle des feuilles de route',
      loading: false,
    });
  }
},




}));
