import { create } from 'zustand';
import axiosInstance from '@/utils/axios';
import { Driver, DriverTimeSlot, DriverAbsence, ScheduleData } from '@/shared/sections/chauffeur/planingChauffeur/types';
import { StatusColor } from '@/shared/sections/chauffeur/planingChauffeur/utils/schedule-utils';
import { ITrajet } from '@/shared/types/trajet';
import { planningDriverEndpoints } from '../endpoints/planningDriver';
import { DailyTripDTO, DailyTripListParams } from '@/shared/types/circuit';
import { circuitEndpoints } from '../endpoints/circuit';

export interface PlanningDriverFilterParams {
  date?: string;
  driverId?: string;
  vehicleId?: string;
  status?: string;
  company?: string;
}

// API Response interface
interface ApiResponse<T> {
  status: 'success' | 'error';
  data: T;
  message?: string;
}

type PlanningDriverStore = {
  timeSlots: DriverTimeSlot[];
  updatedSlot: DriverTimeSlot | null;
  loading: boolean;
  error: string | null;
  successMessage: string | null;
  selectedDate: string;
  totalElements: number;
  dailyTrips: DailyTripDTO[];


  fetchDailySchedule: (date: string, filters?: PlanningDriverFilterParams) => Promise<DriverTimeSlot[]>;
  fetchDailyNonAffected: (date: string, filters?: PlanningDriverFilterParams) => Promise<DriverTimeSlot[]>;
  AffectTrip: (planningId: string, targetDriverId: number) => Promise<ApiResponse<DriverTimeSlot>>;
  reAffectTrip: (planningId: string, targetDriverId: number) => Promise<ApiResponse<DriverTimeSlot>>;
  disAffectTrip: (planningId: string, targetDriverId: string) => Promise<ApiResponse<DriverTimeSlot>>;
  setSelectedDate: (date: string) => void;
  resetError: () => void;
  clearSuccessMessage: () => void;
getAllDailyTrips: (params?: DailyTripListParams) => Promise<void>;

};

export const usePlanningDriverStore = create<PlanningDriverStore>((set, get) => ({
  timeSlots: [],
  dailyTrips: [],
  totalElements: 0,
  updatedSlot: null,
  loading: false,
  error: null,
  successMessage: null,
  selectedDate: new Date().toISOString().split('T')[0],

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

  setSelectedDate: (date: string) => {
    set({ selectedDate: date });
    get().fetchDailySchedule(date);
  },

  fetchDailySchedule: async (date: string, filters?: PlanningDriverFilterParams): Promise<DriverTimeSlot[]> => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get<any>(
        `${planningDriverEndpoints.dailySchedule(date)}`
      );

      const timeSlots = response.data;
      set({
        timeSlots,
        loading: false,
        selectedDate: date,
      });

      return timeSlots;
    } catch (error: any) {
      const message = error?.response?.data?.message || error?.message || 'Failed to fetch daily schedule';
      set({ error: message, loading: false });
      throw new Error(message);
    }
  },

  fetchDailyNonAffected: async (date: string, filters?: PlanningDriverFilterParams): Promise<DriverTimeSlot[]> => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get<any>(
        `${planningDriverEndpoints.dailyNonAffected(date)}`
      );

      const timeSlots = response.data;
      set({
        timeSlots,
        loading: false,
        selectedDate: date,
      });

      return timeSlots;
    } catch (error: any) {
      const message = error?.response?.data?.message || error?.message || 'Failed to fetch daily schedule';
      set({ error: message, loading: false });
      throw new Error(message);
    }
  },

  AffectTrip: async (planningId: string, targetDriverId: number): Promise<ApiResponse<DriverTimeSlot>> => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.post<DriverTimeSlot>(
        planningDriverEndpoints.affectTrip(planningId, targetDriverId)
      );

      const updatedSlot = response.data;
      set({
        updatedSlot,
        loading: false,
        successMessage: 'Trip affected successfully',
      });

      return {
        status: 'success',
        data: updatedSlot,
        message: 'Trip affected successfully'
      };
    } catch (error: any) {
      const message = error?.response?.data?.message || error?.message || 'Failed to affect trip';
      set({ error: message, loading: false });
      
      return {
        status: 'error',
        data: {} as DriverTimeSlot,
        message
      };
    }
  },

  reAffectTrip: async (planningId: string, targetDriverId: number): Promise<ApiResponse<DriverTimeSlot>> => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.post<DriverTimeSlot>(
        planningDriverEndpoints.reAffectTrip(planningId, targetDriverId)
      );

      const updatedSlot = response.data;
      set({
        updatedSlot,
        loading: false,
        successMessage: 'Trip reaffected successfully',
      });

      return {
        status: 'success',
        data: updatedSlot,
        message: 'Trip reaffected successfully'
      };
    } catch (error: any) {
      const message = error?.response?.data?.message || error?.message || 'Failed to reaffect trip';
      set({ error: message, loading: false });
      
      return {
        status: 'error',
        data: {} as DriverTimeSlot,
        message
      };
    }
  },

  disAffectTrip: async (planningId: string, targetDriverId: string): Promise<ApiResponse<DriverTimeSlot>> => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.post<DriverTimeSlot>(
        planningDriverEndpoints.disAffectTrip(planningId, targetDriverId)
      );

      const updatedSlot = response.data;
      set({
        updatedSlot,
        loading: false,
        successMessage: 'Trip disaffected successfully',
      });

      return {
        status: 'success',
        data: updatedSlot,
        message: 'Trip disaffected successfully'
      };
    } catch (error: any) {
      const message = error?.response?.data?.message || error?.message || 'Failed to disaffect trip';
      set({ error: message, loading: false });
      
      return {
        status: 'error',
        data: {} as DriverTimeSlot,
        message
      };
    }
  },
  getAllDailyTrips: async (params?: DailyTripListParams) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get(
        planningDriverEndpoints.getAllDailyTrips,
        { params }
      );
      set({
        loading: false,
        dailyTrips: response.data.content,
        totalElements: response.data.totalElements,
      });
      return response.data;
    } catch (error: any) {
      set({
        error: error.message || 'Erreur lors de la récupération des trajets journaliers',
        loading: false,
      });
      throw error;
    }
  },
}));