import React, { createContext, useContext, ReactNode } from 'react';
import { CounterWithStats, CreateCounterRequest, UpdateCounterRequest, CounterEntry } from '../types';
import { useCounters } from '../hooks/useCounters';

interface CountersContextType {
  counters: CounterWithStats[];
  isLoading: boolean;
  error: string | null;
  version: number;
  createCounter: (data: CreateCounterRequest) => Promise<any>;
  updateCounter: (id: number | string, data: UpdateCounterRequest) => Promise<any>;
  deleteCounter: (id: number | string) => Promise<void>;
  incrementCounter: (id: number | string, value: number) => Promise<any>;
  getCounterEntries: (id: number | string) => Promise<CounterEntry[]>;
  searchCounters: (search: string) => void;
  refreshCounters: () => Promise<void>;
}

const CountersContext = createContext<CountersContextType | undefined>(undefined);

interface CountersProviderProps {
  children: ReactNode;
}

export const CountersProvider: React.FC<CountersProviderProps> = ({ children }) => {
  const countersData = useCounters();

  return (
    <CountersContext.Provider value={countersData}>
      {children}
    </CountersContext.Provider>
  );
};

export const useCountersContext = (): CountersContextType => {
  const context = useContext(CountersContext);
  if (context === undefined) {
    throw new Error('useCountersContext must be used within a CountersProvider');
  }
  return context;
};
