import React, { createContext, useContext } from 'react';
import type { Identifier } from '../../types/identifiers';

export interface DocumentsFilterValue {
  query: string;
  searchResultIds: Array<string> | null;
  searchLoading: boolean;
  includeDescendants: boolean;
  activeTagIds: Identifier[];
  activeCorrespondentIds: Identifier[];
  isActive: boolean;
  setQuery: (value: string) => void;
  submit: () => void;
  clear: () => void;
  toggleTag: (tagId: Identifier) => void;
  toggleCorrespondent: (correspondentId?: Identifier | null) => void;
  toggleIncludeDescendants: () => void;
}

const DocumentsFilterContext = createContext<DocumentsFilterValue | null>(null);

interface DocumentsFilterProviderProps {
  value: DocumentsFilterValue;
  children: React.ReactNode;
}

export const DocumentsFilterProvider: React.FC<DocumentsFilterProviderProps> = ({ value, children }) => (
  <DocumentsFilterContext.Provider value={value}>{children}</DocumentsFilterContext.Provider>
);

export const useDocumentsFilter = (): DocumentsFilterValue => {
  const context = useContext(DocumentsFilterContext);
  if (!context) {
    throw new Error('useDocumentsFilter must be used within a DocumentsFilterProvider');
  }
  return context;
};

export default DocumentsFilterContext;
