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

type DocumentOpenTarget = 'preview' | 'sidepanel' | 'viewer';

interface DocumentOpenContextValue {
    openDocument: (doc: Document, target?: DocumentOpenTarget) => void;
}

const DocumentOpenContext = createContext<DocumentOpenContextValue | null>(null);

export const useDocumentOpen = () => {
    const context = useContext(DocumentOpenContext);
    if (!context) {
        throw new Error('useDocumentOpen must be used within a DocumentOpenProvider');
    }
    return context;
};

interface DocumentOpenProviderProps {
    children: React.ReactNode;
    onOpenViewer?: (docId: Identifier) => void;
    onOpenPreview?: (doc: Document) => void;
    onOpenSidepanel?: (docId: Identifier) => void;
}

export const DocumentOpenProvider: React.FC<DocumentOpenProviderProps> = ({
    children,
    onOpenViewer,
    onOpenPreview,
    onOpenSidepanel,
}) => {
    const openDocument = useCallback((doc: Document, target: DocumentOpenTarget = 'preview') => {
        if (!doc) return;

        switch (target) {
            case 'preview':
                if (onOpenPreview) {
                    onOpenPreview(doc);
                }
                break;
            case 'sidepanel':
                if (onOpenSidepanel) {
                    onOpenSidepanel(doc.id);
                }
                break;
            case 'viewer':
                if (onOpenViewer) {
                    onOpenViewer(doc.id);
                }
                break;
        }
    }, [onOpenPreview, onOpenSidepanel, onOpenViewer]);

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