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

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


type RoadMapStore = {
  validatedRoadMap: IRoadmap[];
  submittedRoadMaps: SubmittedRoadMapDTO[];
  oldSubmittedRoadMaps: IOldRoadmap[];
  loading: boolean;
  error: string | null;
  getAllValidRoadMap: (params?: RoadMapPageFilterParams) => Promise<void>;
  getAllSubmittedRoadMaps: (params?: SubmittedRoadMapFilterParams) => Promise<void>;
  getOldSubmittedRoadMaps: (params: OldSubmittedRoadMapFilterParams) => Promise<void>;
  totalElements: number;
};

export const useRoadMapStore = create<RoadMapStore>((set) => ({
  validatedRoadMap: [],
  submittedRoadMaps: [],
  oldSubmittedRoadMaps: [],
  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 });
    }
  },
  
}));
