import React, { createContext, useContext, ReactNode } from 'react';
import { usePek } from '../hooks/usePek';

interface PekContextType {
  // Location input - separate fields
  kanton: string;
  setKanton: (value: string) => void;
  gemeinde: string;
  setGemeinde: (value: string) => void;
  adresse: string;
  setAdresse: (value: string) => void;
  buildLocationString: () => string;
  // Legacy locationInput for backward compatibility
  locationInput: string;
  setLocationInput: (value: string) => void;
  useCurrentLocation: () => Promise<void>;
  isGettingLocation: boolean;
  locationError: string | null;

  // Parcel search
  selectedParcels: any[];
  searchParcel: (location: string, includeAdjacent?: boolean) => Promise<any>;
  isSearchingParcel: boolean;
  parcelSearchError: string | null;
  removeParcel: (parcelId: string) => void;
  clearSelectedParcels: () => void;
  isParcelSelected: (parcelId: string) => boolean;

  // Map view
  mapCenter: any;
  mapZoomBounds: any;
  parcelGeometries: any[];
  handleMapClick: (point: any) => Promise<void>;
  handleParcelClick: (parcelId: string) => Promise<void>;

  // Command processing
  commandInput: string;
  setCommandInput: (value: string) => void;
  processCommand: (userInput: string) => Promise<any>;
  isProcessingCommand: boolean;
  commandResults: any[];
  commandError: string | null;

  // Project management
  currentProjekt: any;
  createProjekt: (data: any) => Promise<any>;
  isCreatingProjekt: boolean;
  addParcelToProjekt: (projektId: string, data: any) => Promise<any>;
  isAddingParcel: boolean;
  projektError: string | null;

  // Panel state
  isPanelOpen: boolean;
  setIsPanelOpen: (open: boolean) => void;
}

const PekContext = createContext<PekContextType | undefined>(undefined);

export const PekProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const pekData = usePek();
  
  return (
    <PekContext.Provider value={pekData}>
      {children}
    </PekContext.Provider>
  );
};

export const usePekContext = (): PekContextType => {
  const context = useContext(PekContext);
  if (!context) {
    throw new Error('usePekContext must be used within a PekProvider');
  }
  return context;
};

