import useExamEditorStore from '@/stores/examEditor';
import ExamEditorStore from '@/stores/examEditor/types';
import { useCallback, useState } from 'react';

interface Props {
    sectionId: number;
    mode?: "delete" | "edit";
    editing?: boolean;
    setEditing?: React.Dispatch<React.SetStateAction<boolean>>;
    onSave?: () => void;
    onDiscard?: () => void;
    onMode?: () => void;
}

const useSectionEdit = ({
    sectionId,
    editing: externalEditing = false,
    setEditing: externalSetEditing,
    onSave,
    onDiscard,
    onMode
}: Props) => {
    const { dispatch } = useExamEditorStore();
    const [internalEditing, setInternalEditing] = useState<boolean>(externalEditing);
    const editing = externalSetEditing !== undefined ? externalEditing : internalEditing;
    const setEditing = externalSetEditing !== undefined ? externalSetEditing : setInternalEditing;


    const updateRoot = useCallback((updates: Partial<ExamEditorStore>) => {
        dispatch({ type: 'UPDATE_ROOT', payload: { updates } });
    }, [dispatch]);

    const handleEdit = useCallback(() => {
        setEditing(true);
    }, [sectionId, setEditing, updateRoot]);

    const handleSave = useCallback(() => {
        if (onSave) {
            onSave();
        } else {
            setEditing(false);
        }

    }, [setEditing, updateRoot, onSave, sectionId]);

    const handleDiscard = useCallback(() => {
        setEditing(false);
        onDiscard?.();
    }, [setEditing, updateRoot, onDiscard, sectionId]);

    const modeHandle = useCallback(() => {
        setEditing(!editing);
        onMode?.();

    }, [setEditing, editing, updateRoot, onMode, sectionId]);

    return {
        editing,
        setEditing,
        handleEdit,
        handleSave,
        handleDiscard,
        modeHandle,
    };
};

export default useSectionEdit;
