/**
 * 页面动作执行器
 * 将解析后的页面动作映射到路由与页面状态更新
 */

import { toast } from 'sonner';
import { 
  PageAction, 
  Tab, 
  validatePageAction, 
  getActionTypeLabel, 
  getTabLabel 
} from './pageActions';

// Tab 到路由路径的映射
export const tabToPath: Record<Tab, string> = {
  home: '/admin',
  products: '/admin',
  transactions: '/admin',
  marketing: '/admin',
  aftersales: '/admin',
};

// 页面状态接口
export interface PageStateManager {
  setTab: (tab: Tab) => void;
  setSearch: (keyword: string) => void;
  setSort: (field: string, direction: 'asc' | 'desc') => void;
  setFilters: (filters: Record<string, any>) => void;
  mergeFilters: (filters: Record<string, any>) => void;
  clearFilters: () => void;
  refresh: () => void;
}

// 路由接口
export interface RouterInterface {
  push?: (path: string) => void;
  navigate: (path: string) => void;
}

// 执行选项
export interface ExecuteOptions {
  router?: RouterInterface;
  state?: Partial<PageStateManager>;
  onNavigate?: (tab: string) => void;
  emitPageState?: (state: any) => void;
  showToast?: boolean;
  debug?: boolean;
}

// 执行结果
export interface ExecuteResult {
  success: boolean;
  action: PageAction;
  message: string;
  latency?: number;
}

/**
 * 执行页面动作
 */
export async function executePageAction(
  action: PageAction,
  options: ExecuteOptions
): Promise<ExecuteResult> {
  const startTime = performance.now();
  const { 
    router, 
    state, 
    onNavigate, 
    emitPageState,
    showToast = true, 
    debug = false 
  } = options;

  // 校验动作
  const validation = validatePageAction(action);
  if (!validation.ok) {
    const errorMsg = `动作参数不完整: 缺少 ${validation.missing?.join(', ')}`;
    if (showToast) toast.error(errorMsg);
    return {
      success: false,
      action,
      message: errorMsg,
      latency: performance.now() - startTime,
    };
  }

  // 显示警告
  if (validation.warnings && debug) {
    validation.warnings.forEach(w => console.warn('PageAction 警告:', w));
  }

  const params = action.params as any;
  const tab = params.tab as Tab;
  let message = '';

  try {
    switch (action.type) {
      case 'navigate_to_page':
        // 直接路由跳转（如创建优惠券页面）
        const path = params.path;
        if (path && router?.navigate) {
          router.navigate(path);
          message = `正在跳转...`;
        } else if (path && router?.push) {
          router.push(path);
          message = `正在跳转...`;
        } else {
          message = '无法执行跳转';
        }
        break;

      case 'navigate':
        // 导航到指定 Tab
        if (onNavigate) {
          onNavigate(tab);
        }
        if (router?.navigate) {
          router.navigate(tabToPath[tab]);
        } else if (router?.push) {
          router.push(tabToPath[tab]);
        }
        message = `已导航到${getTabLabel(tab)}`;
        break;

      case 'search':
        // 执行搜索
        if (onNavigate) {
          onNavigate(tab);
        }
        if (emitPageState) {
          emitPageState({
            tab,
            search: params.keyword || '',
          });
        }
        if (state?.setSearch) {
          state.setSearch(params.keyword || '');
        }
        message = params.keyword 
          ? `已在${getTabLabel(tab)}搜索: "${params.keyword}"`
          : `已清除${getTabLabel(tab)}的搜索`;
        break;

      case 'sort':
        // 执行排序
        if (onNavigate) {
          onNavigate(tab);
        }
        if (emitPageState) {
          emitPageState({
            tab,
            sort: {
              field: params.field,
              direction: params.direction || 'desc',
            },
          });
        }
        if (state?.setSort) {
          state.setSort(params.field, params.direction || 'desc');
        }
        message = `已按 ${params.field} ${params.direction === 'asc' ? '升序' : '降序'} 排序`;
        break;

      case 'filter':
        // 执行筛选
        if (onNavigate) {
          onNavigate(tab);
        }
        if (emitPageState) {
          emitPageState({
            tab,
            filters: params.filters || {},
          });
        }
        if (state?.setFilters) {
          state.setFilters(params.filters || {});
        }
        const filterCount = Object.keys(params.filters || {}).length;
        message = filterCount > 0
          ? `已应用 ${filterCount} 个筛选条件`
          : `已清除所有筛选条件`;
        break;

      case 'set_page_state':
        // 综合设置页面状态
        if (onNavigate) {
          onNavigate(tab);
        }
        if (emitPageState) {
          emitPageState({
            tab,
            filters: params.filters,
            sort: params.sort,
            search: params.search,
          });
        }
        // 逐个应用状态
        if (params.search !== undefined && state?.setSearch) {
          state.setSearch(params.search);
        }
        if (params.sort && state?.setSort) {
          state.setSort(params.sort.field, params.sort.direction);
        }
        if (params.filters && state?.setFilters) {
          state.setFilters(params.filters);
        }
        if (state?.refresh) {
          state.refresh();
        }
        message = '页面状态已更新';
        break;

      default:
        message = `未知的动作类型: ${action.type}`;
        if (showToast) toast.error(message);
        return {
          success: false,
          action,
          message,
          latency: performance.now() - startTime,
        };
    }

    if (showToast) {
      toast.success(message);
    }

    // 日志与埋点
    if (debug) {
      console.log('PageAction 执行成功:', {
        type: action.type,
        tab,
        params,
        message,
        latency: performance.now() - startTime,
      });
    }

    // 可选：发送埋点
    trackPageAction({
      type: action.type,
      tab,
      success: true,
      latency: performance.now() - startTime,
    });

    return {
      success: true,
      action,
      message,
      latency: performance.now() - startTime,
    };
  } catch (error) {
    const errorMsg = `执行${getActionTypeLabel(action.type)}失败: ${error instanceof Error ? error.message : '未知错误'}`;
    if (showToast) toast.error(errorMsg);
    
    trackPageAction({
      type: action.type,
      tab,
      success: false,
      latency: performance.now() - startTime,
      error: errorMsg,
    });

    return {
      success: false,
      action,
      message: errorMsg,
      latency: performance.now() - startTime,
    };
  }
}

/**
 * 埋点追踪
 */
interface TrackData {
  type: string;
  tab: Tab;
  success: boolean;
  latency: number;
  error?: string;
}

function trackPageAction(data: TrackData): void {
  // 发送到分析系统（可扩展）
  console.log('[PageAction Track]', data);
  
  // 可以接入实际的分析系统
  // analytics.track('page_action', data);
}

/**
 * 批量执行页面动作
 */
export async function executePageActions(
  actions: PageAction[],
  options: ExecuteOptions
): Promise<ExecuteResult[]> {
  const results: ExecuteResult[] = [];
  
  for (const action of actions) {
    const result = await executePageAction(action, {
      ...options,
      showToast: false, // 批量执行时不显示单个 toast
    });
    results.push(result);
    
    // 如果某个动作失败，可以选择继续或停止
    if (!result.success && options.debug) {
      console.warn('动作执行失败，继续执行下一个:', result.message);
    }
  }

  // 批量执行完成后显示汇总
  const successCount = results.filter(r => r.success).length;
  const failCount = results.length - successCount;
  
  if (options.showToast !== false) {
    if (failCount === 0) {
      toast.success(`成功执行 ${successCount} 个操作`);
    } else {
      toast.warning(`执行完成: ${successCount} 成功, ${failCount} 失败`);
    }
  }

  return results;
}
