/**
 * 仪表板状态管理 Hook
 * 用于管理店长视窗的组件显示、布局和数据刷新
 */
import { useState, useCallback, useEffect } from 'react';
import { toast } from 'sonner';
import {
  DashboardState,
  DashboardAction,
  DEFAULT_DASHBOARD_STATE,
  executeDashboardAction,
  extractDashboardAction,
  WidgetId,
  LayoutMode,
  TimeRange,
  PRESET_LAYOUTS
} from '@/ai/dashboardActions';

// 本地存储键
const STORAGE_KEY = 'dashboard_state';

export interface UseDashboardStateReturn {
  state: DashboardState;
  isWidgetVisible: (widgetId: WidgetId) => boolean;
  isFocused: (widgetId: WidgetId) => boolean;
  
  // 动作执行
  executeAction: (action: DashboardAction) => void;
  parseAndExecute: (text: string) => boolean;
  
  // 直接操作
  showWidget: (widgetId: WidgetId) => void;
  hideWidget: (widgetId: WidgetId) => void;
  toggleWidget: (widgetId: WidgetId) => void;
  setLayout: (layout: LayoutMode) => void;
  focusWidget: (widgetId: WidgetId | null) => void;
  setTimeRange: (range: TimeRange) => void;
  resetToDefault: () => void;
  
  // 刷新信号
  refreshSignal: Record<WidgetId, number>;
  triggerRefresh: (widgetIds: WidgetId[]) => void;
}

export function useDashboardState(): UseDashboardStateReturn {
  // 从本地存储加载初始状态
  const [state, setState] = useState<DashboardState>(() => {
    try {
      const saved = localStorage.getItem(STORAGE_KEY);
      if (saved) {
        const parsed = JSON.parse(saved);
        return { ...DEFAULT_DASHBOARD_STATE, ...parsed };
      }
    } catch (e) {
      console.warn('Failed to load dashboard state from storage:', e);
    }
    return DEFAULT_DASHBOARD_STATE;
  });

  // 刷新信号（用于触发组件刷新）
  const [refreshSignal, setRefreshSignal] = useState<Record<WidgetId, number>>({} as Record<WidgetId, number>);

  // 保存状态到本地存储
  useEffect(() => {
    try {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
    } catch (e) {
      console.warn('Failed to save dashboard state:', e);
    }
  }, [state]);

  // 检查组件是否可见
  const isWidgetVisible = useCallback((widgetId: WidgetId): boolean => {
    return state.visibleWidgets.includes(widgetId);
  }, [state.visibleWidgets]);

  // 检查组件是否聚焦
  const isFocused = useCallback((widgetId: WidgetId): boolean => {
    return state.focusedWidget === widgetId;
  }, [state.focusedWidget]);

  // 执行仪表板动作
  const executeAction = useCallback((action: DashboardAction) => {
    const result = executeDashboardAction(action, state);
    
    if (result.success) {
      setState(result.newState);
      toast.success(result.message);
      
      // 如果是刷新动作，触发刷新信号
      if (action.type === 'refresh_widget' && action.params) {
        const params = action.params as { widgets: WidgetId[] };
        triggerRefreshInternal(params.widgets);
      }
    } else {
      toast.error(result.message);
    }
  }, [state]);

  // 内部刷新触发
  const triggerRefreshInternal = (widgetIds: WidgetId[]) => {
    setRefreshSignal(prev => {
      const newSignal = { ...prev };
      widgetIds.forEach(id => {
        newSignal[id] = (prev[id] || 0) + 1;
      });
      return newSignal;
    });
  };

  // 解析文本并执行动作
  const parseAndExecute = useCallback((text: string): boolean => {
    const action = extractDashboardAction(text);
    if (action) {
      executeAction(action);
      return true;
    }
    return false;
  }, [executeAction]);

  // 显示组件
  const showWidget = useCallback((widgetId: WidgetId) => {
    setState(prev => {
      if (prev.visibleWidgets.includes(widgetId)) return prev;
      return {
        ...prev,
        visibleWidgets: [...prev.visibleWidgets, widgetId],
        layout: 'custom'
      };
    });
  }, []);

  // 隐藏组件
  const hideWidget = useCallback((widgetId: WidgetId) => {
    setState(prev => ({
      ...prev,
      visibleWidgets: prev.visibleWidgets.filter(w => w !== widgetId),
      layout: 'custom',
      focusedWidget: prev.focusedWidget === widgetId ? null : prev.focusedWidget
    }));
  }, []);

  // 切换组件显示
  const toggleWidget = useCallback((widgetId: WidgetId) => {
    setState(prev => {
      const visible = prev.visibleWidgets.includes(widgetId);
      return {
        ...prev,
        visibleWidgets: visible 
          ? prev.visibleWidgets.filter(w => w !== widgetId)
          : [...prev.visibleWidgets, widgetId],
        layout: 'custom',
        focusedWidget: visible && prev.focusedWidget === widgetId ? null : prev.focusedWidget
      };
    });
  }, []);

  // 设置布局
  const setLayout = useCallback((layout: LayoutMode) => {
    if (layout === 'custom') return;
    
    setState(prev => ({
      ...prev,
      visibleWidgets: [...PRESET_LAYOUTS[layout]],
      layout,
      focusedWidget: null
    }));
    
    const layoutNames: Record<LayoutMode, string> = {
      default: '默认布局',
      compact: '紧凑布局',
      analytics: '数据分析',
      approvals: '审批视图',
      custom: '自定义'
    };
    toast.success(`已切换到${layoutNames[layout]}`);
  }, []);

  // 聚焦组件
  const focusWidget = useCallback((widgetId: WidgetId | null) => {
    setState(prev => {
      // 确保组件可见
      let visibleWidgets = prev.visibleWidgets;
      if (widgetId && !visibleWidgets.includes(widgetId)) {
        visibleWidgets = [...visibleWidgets, widgetId];
      }
      return {
        ...prev,
        visibleWidgets,
        focusedWidget: widgetId
      };
    });
  }, []);

  // 设置时间范围
  const setTimeRange = useCallback((range: TimeRange) => {
    setState(prev => ({ ...prev, timeRange: range }));
    
    const rangeNames: Record<TimeRange, string> = {
      today: '今日',
      week: '本周',
      month: '本月',
      quarter: '本季度',
      year: '本年'
    };
    toast.success(`数据范围已设置为${rangeNames[range]}`);
  }, []);

  // 重置为默认状态
  const resetToDefault = useCallback(() => {
    setState(DEFAULT_DASHBOARD_STATE);
    toast.success('已重置为默认布局');
  }, []);

  // 触发刷新
  const triggerRefresh = useCallback((widgetIds: WidgetId[]) => {
    triggerRefreshInternal(widgetIds);
    toast.success(`正在刷新: ${widgetIds.join(', ')}`);
  }, []);

  return {
    state,
    isWidgetVisible,
    isFocused,
    executeAction,
    parseAndExecute,
    showWidget,
    hideWidget,
    toggleWidget,
    setLayout,
    focusWidget,
    setTimeRange,
    resetToDefault,
    refreshSignal,
    triggerRefresh
  };
}
