import React, { createContext, useContext, useState, ReactNode, useMemo, useCallback } from 'react';

interface PageHeaderContextType {
  title: string | null;
  action: ReactNode | null;
  setPageHeader: (title: string | null, action?: ReactNode) => void;
  clearPageHeader: () => void;
}

const PageHeaderContext = createContext<PageHeaderContextType | undefined>(undefined);

export function PageHeaderProvider({ children }: { children: ReactNode }) {
  const [title, setTitle] = useState<string | null>(null);
  const [action, setAction] = useState<ReactNode | null>(null);

  const setPageHeader = useCallback((newTitle: string | null, newAction?: ReactNode) => {
    setTitle(newTitle);
    setAction(newAction || null);
  }, []);

  const clearPageHeader = useCallback(() => {
    setTitle(null);
    setAction(null);
  }, []);

  const value = useMemo(() => ({ title, action, setPageHeader, clearPageHeader }), [title, action, setPageHeader, clearPageHeader]);

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

export function usePageHeader() {
  const context = useContext(PageHeaderContext);
  if (!context) {
    throw new Error('usePageHeader must be used within PageHeaderProvider');
  }
  return context;
}
