'use client';

import { createContext, useContext, ReactNode, useCallback, useRef, useEffect } from 'react';
import { usePathname } from 'next/navigation';
import { useTaskPolling, PollingTask, TaskState } from '@/hooks/useTaskPolling';
import { useAuthStore } from '@/store/authStore';

interface TaskPollingContextType {
  /** 开始轮询任务 */
  startPolling: (params: PollingTask) => void;
  /** 停止轮询任务 */
  stopPolling: (taskId: string) => void;
  /** 获取任务状态 */
  getTaskState: (taskId: string) => TaskState | undefined;
  /** 停止所有轮询 */
  stopAll: () => void;
}

const TaskPollingContext = createContext<TaskPollingContextType | null>(null);

/**
 * 任务轮询 Provider - 替代 WebSocketProvider
 *
 * 仅在项目页面启用任务轮询功能
 */
export function TaskPollingProvider({ children }: { children: ReactNode }) {
  const pathname = usePathname();
  const { user } = useAuthStore();
  const isProjectPage =
    pathname != null &&
    pathname.startsWith('/project/') &&
    pathname !== '/project' &&
    pathname.length > '/project/'.length;

  const enabled = isProjectPage && !!user?.id;

  const { startPolling, stopPolling, getTaskState, stopAll } = useTaskPolling({
    defaultInterval: 5000,
    fastPollInterval: 2000,
    fastPollAttempts: 6,
    maxAttempts: 120,
    enableNotifications: true,
  });

  // 离开项目页面时停止所有轮询
  const prevEnabledRef = useRef(enabled);
  useEffect(() => {
    if (prevEnabledRef.current && !enabled) {
      stopAll();
    }
    prevEnabledRef.current = enabled;
  }, [enabled, stopAll]);

  const handleStartPolling = useCallback(
    (params: PollingTask) => {
      if (!enabled) {
        console.warn('Task polling is disabled outside project pages');
        return;
      }
      startPolling(params);
    },
    [enabled, startPolling]
  );

  return (
    <TaskPollingContext.Provider
      value={{
        startPolling: handleStartPolling,
        stopPolling,
        getTaskState,
        stopAll,
      }}
    >
      {children}
    </TaskPollingContext.Provider>
  );
}

/**
 * 使用任务轮询上下文的 Hook
 *
 * @returns TaskPollingContextType 轮询上下文对象
 * @throws 如果在 TaskPollingProvider 外部使用会抛出错误
 *
 * @example
 * ```tsx
 * function MyComponent() {
 *   const { startPolling, getTaskState } = useTaskPollingContext();
 *
 *   const handleGenerate = async () => {
 *     const taskId = await generateImage();
 *     startPolling({
 *       taskId,
 *       taskType: 'image',
 *       onComplete: (result) => {
 *         console.log('Task completed:', result);
 *       }
 *     });
 *   };
 *
 *   return <button onClick={handleGenerate}>Generate</button>;
 * }
 * ```
 */
export function useTaskPollingContext() {
  const context = useContext(TaskPollingContext);
  if (!context) {
    throw new Error('useTaskPollingContext must be used within TaskPollingProvider');
  }
  return context;
}
