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

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

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

const [DocumentOpenContext, useDocumentOpen] = createSafeContext<DocumentOpenContextValue>('DocumentOpen');

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>
    );
};

export { useDocumentOpen };
