import React, { createContext, useContext, useEffect, useState } from 'react';

interface CurrentTripContextType {
  currentTripId: string | null;
  setCurrentTripId: (tripId: string | null) => void;
  activeDayId: string | null;
  setActiveDayId: (dayId: string | null) => void;
}

const CurrentTripContext = createContext<CurrentTripContextType | undefined>(undefined);

export const CurrentTripProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [currentTripId, setCurrentTripId] = useState<string | null>(null);
  const [activeDayId, setActiveDayId] = useState<string | null>(null);

  // LocalStorage'dan yükle
  useEffect(() => {
    const storedTripId = localStorage.getItem('currentTripId');
    const storedDayId = localStorage.getItem('activeDayId');
    if (storedTripId) {
      setCurrentTripId(storedTripId);
    }
    if (storedDayId) {
      setActiveDayId(storedDayId);
    }
  }, []);

  // LocalStorage'a kaydet - Trip ID
  const handleSetCurrentTripId = (tripId: string | null) => {
    setCurrentTripId(tripId);
    if (tripId) {
      localStorage.setItem('currentTripId', tripId);
    } else {
      localStorage.removeItem('currentTripId');
      // Trip silindiğinde active day'i de temizle
      handleSetActiveDayId(null);
    }
  };

  // LocalStorage'a kaydet - Active Day ID
  const handleSetActiveDayId = (dayId: string | null) => {
    setActiveDayId(dayId);
    if (dayId) {
      localStorage.setItem('activeDayId', dayId);
    } else {
      localStorage.removeItem('activeDayId');
    }
  };

  return (
    <CurrentTripContext.Provider value={{ 
      currentTripId, 
      setCurrentTripId: handleSetCurrentTripId,
      activeDayId,
      setActiveDayId: handleSetActiveDayId
    }}>
      {children}
    </CurrentTripContext.Provider>
  );
};

export const useCurrentTrip = () => {
  const context = useContext(CurrentTripContext);
  if (context === undefined) {
    throw new Error('useCurrentTrip must be used within a CurrentTripProvider');
  }
  return context;
};