'use client';

import React, { createContext, useContext, useState, ReactNode, useCallback } from 'react';
import { PageInfo } from '../site-header';



export interface DashboardParams {
    pageInfo: PageInfo;
}

interface DashboardContextType {
    Dashboard: DashboardParams;
    setDashboard: (info: DashboardParams) => void;
}

const defaultDashboard: DashboardParams = {
    pageInfo: {
        title: '文档管理',
    },
};

const DashboardContext = createContext<DashboardContextType | undefined>(undefined);

export function DashboardProvider({ children }: { children: ReactNode }) {
    const [Dashboard, setDashboardState] = useState<DashboardParams>(defaultDashboard);

    const setDashboard = useCallback((info: DashboardParams) => {
        setDashboardState(info);
    }, []);

    return (
        <DashboardContext.Provider value={{ Dashboard, setDashboard }}>
            {children}
        </DashboardContext.Provider>
    );
}

export function useDashboard() {
    const context = useContext(DashboardContext);
    if (context === undefined) {
        throw new Error('useDashboard must be used within a DashboardProvider');
    }
    return context;
}

export function useSetDashboard(Dashboard: DashboardParams) {
    const { setDashboard } = useDashboard();

    React.useEffect(() => {
        setDashboard(Dashboard);
    }, [Dashboard.pageInfo.title, Dashboard.pageInfo.subtitle, Dashboard.pageInfo.rightContent, setDashboard]);
}

export function useSetPageInfo(pageInfo: PageInfo) {
    const { setDashboard } = useDashboard();

    React.useEffect(() => {
        setDashboard({ pageInfo });
    }, [pageInfo.title, pageInfo.subtitle, pageInfo.rightContent, setDashboard]);
}
