import { useState, useRef, useEffect, useMemo } from 'react';
import { useDataRequest, useTaskProgress } from '@/hooks/useApi';

interface AnalysisState {
  content: string;
  loading: boolean;
  error: string | null;
  elapsed_ms?: number;
}

interface AnalysisRecord {
  type: string;
  name: string;
  status: 'pending' | 'running' | 'done' | 'error';
  start_ts?: string;
  end_ts?: string;
  duration_ms?: number;
  tokens?: {
    prompt_tokens: number;
    completion_tokens: number;
    total_tokens: number;
  };
  error?: string;
}

export function useAnalysisRunner(
  financials: any,
  analysisConfig: any,
  normalizedMarket: string,
  unifiedSymbol: string,
  isLoading: boolean,
  error: any
) {
  // 分析类型列表
  const analysisTypes = useMemo(() => {
    if (!analysisConfig?.analysis_modules) return [];
    return Object.keys(analysisConfig.analysis_modules);
  }, [analysisConfig]);

  // 分析状态管理
  const [analysisStates, setAnalysisStates] = useState<Record<string, AnalysisState>>({});
  
  const fullAnalysisTriggeredRef = useRef<boolean>(false);
  const isAnalysisRunningRef = useRef<boolean>(false);
  const analysisFetchedRefs = useRef<Record<string, boolean>>({});
  const stopRequestedRef = useRef<boolean>(false);
  const abortControllerRef = useRef<AbortController | null>(null);
  const currentAnalysisTypeRef = useRef<string | null>(null);
  const [manualRunKey, setManualRunKey] = useState(0);
  
  // 当前正在执行的分析任务
  const [currentAnalysisTask, setCurrentAnalysisTask] = useState<string | null>(null);
  
  // 计时器状态
  const [startTime, setStartTime] = useState<number | null>(null);
  const [elapsedSeconds, setElapsedSeconds] = useState(0);
  
  // 分析执行记录
  const [analysisRecords, setAnalysisRecords] = useState<AnalysisRecord[]>([]);

  // 新架构：触发分析与查看任务进度
  const { trigger: triggerAnalysisRequest, isMutating: triggering } = useDataRequest();
  const [requestId, setRequestId] = useState<string | null>(null);
  const { progress: taskProgress } = useTaskProgress(requestId);

  // 计算完成比例
  const completionProgress = useMemo(() => {
    const totalTasks = analysisRecords.length;
    if (totalTasks === 0) return 0;
    const completedTasks = analysisRecords.filter(r => r.status === 'done' || r.status === 'error').length;
    return (completedTasks / totalTasks) * 100;
  }, [analysisRecords]);

  // 总耗时（ms）
  const totalElapsedMs = useMemo(() => {
    const finMs = financials?.meta?.elapsed_ms || 0;
    const analysesMs = analysisRecords.reduce((sum, r) => sum + (r.duration_ms || 0), 0);
    return finMs + analysesMs;
  }, [financials?.meta?.elapsed_ms, analysisRecords]);

  const hasRunningTask = useMemo(() => {
    if (currentAnalysisTask !== null) return true;
    if (analysisRecords.some(r => r.status === 'running')) return true;
    return false;
  }, [currentAnalysisTask, analysisRecords]);

  // 全部任务是否完成
  const allTasksCompleted = useMemo(() => {
    if (analysisRecords.length === 0) return false;
    const allDoneOrErrored = analysisRecords.every(r => r.status === 'done' || r.status === 'error');
    return allDoneOrErrored && !hasRunningTask && currentAnalysisTask === null;
  }, [analysisRecords, hasRunningTask, currentAnalysisTask]);

  // 所有任务完成时，停止计时器
  useEffect(() => {
    if (allTasksCompleted) {
      setStartTime(null);
    }
  }, [allTasksCompleted]);

  useEffect(() => {
    if (!startTime) return;
    const interval = setInterval(() => {
      const now = Date.now();
      const elapsed = Math.floor((now - startTime) / 1000);
      setElapsedSeconds(elapsed);
    }, 1000);
    return () => clearInterval(interval);
  }, [startTime]);

  const retryAnalysis = async (analysisType: string) => {
    if (!financials || !analysisConfig?.analysis_modules) {
      return;
    }
    analysisFetchedRefs.current[analysisType] = false;
    setAnalysisStates(prev => ({
      ...prev,
      [analysisType]: { content: '', loading: true, error: null }
    }));
    setAnalysisRecords(prev => prev.filter(record => record.type !== analysisType));
    const analysisName =
      analysisConfig.analysis_modules[analysisType]?.name || analysisType;
    const startTimeISO = new Date().toISOString();
    setCurrentAnalysisTask(analysisType);
    setAnalysisRecords(prev => [...prev, {
      type: analysisType,
      name: analysisName,
      status: 'running',
      start_ts: startTimeISO
    }]);

    try {
      const startedMsLocal = Date.now();
      const response = await fetch(
        `/api/financials/${normalizedMarket}/${unifiedSymbol}/analysis/${analysisType}/stream?company_name=${encodeURIComponent(financials?.name || unifiedSymbol)}`
      );
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const reader = response.body?.getReader();
      const decoder = new TextDecoder();
      let aggregate = '';
      if (reader) {
        while (true) {
          const { value, done } = await reader.read();
          if (done) break;
          const chunk = decoder.decode(value, { stream: true });
          aggregate += chunk;
          const snapshot = aggregate;
          setAnalysisStates(prev => ({
            ...prev,
            [analysisType]: {
              ...prev[analysisType],
              content: snapshot,
              loading: true,
              error: null,
            }
          }));
        }
      }
      const endTime = new Date().toISOString();
      const elapsedMs = Date.now() - startedMsLocal;
      setAnalysisStates(prev => ({
        ...prev,
        [analysisType]: {
          ...prev[analysisType],
          content: aggregate,
          loading: false,
          error: null,
          elapsed_ms: elapsedMs,
        }
      }));
      setAnalysisRecords(prev => prev.map(record =>
        record.type === analysisType
          ? {
              ...record,
              status: 'done',
              end_ts: endTime,
              duration_ms: elapsedMs,
            }
          : record
      ));
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '加载失败';
      const endTime = new Date().toISOString();
      setAnalysisStates(prev => ({
        ...prev,
        [analysisType]: {
          content: '',
          loading: false,
          error: errorMessage
        }
      }));
      setAnalysisRecords(prev => prev.map(record =>
        record.type === analysisType
          ? {
              ...record,
              status: 'error',
              end_ts: endTime,
              error: errorMessage
            }
          : record
      ));
    } finally {
      setCurrentAnalysisTask(null);
      analysisFetchedRefs.current[analysisType] = true;
    }
  };

  useEffect(() => {
    if (isLoading || error || !financials || !analysisConfig?.analysis_modules || analysisTypes.length === 0) {
      return;
    }
    if (isAnalysisRunningRef.current) {
      return;
    }
    const runAnalysesSequentially = async () => {
      if (isAnalysisRunningRef.current) {
        return;
      }
      isAnalysisRunningRef.current = true;
      try {
        if (!stopRequestedRef.current && !startTime) {
          setStartTime(Date.now());
        }
        for (let i = 0; i < analysisTypes.length; i++) {
          const analysisType = analysisTypes[i];
          if (stopRequestedRef.current) {
            break;
          }
          if (analysisFetchedRefs.current[analysisType]) {
            continue;
          }
          if (!analysisFetchedRefs.current || !analysisConfig?.analysis_modules) {
            console.error("分析配置或refs未初始化，无法进行分析。");
            continue;
          }
          currentAnalysisTypeRef.current = analysisType;
          const analysisName =
            analysisConfig.analysis_modules[analysisType]?.name || analysisType;
          const startTimeISO = new Date().toISOString();
          setCurrentAnalysisTask(analysisType);
          setAnalysisRecords(prev => {
            const next = [...prev];
            const idx = next.findIndex(r => r.type === analysisType);
            const updated: AnalysisRecord = {
              type: analysisType,
              name: analysisName,
              status: 'running' as const,
              start_ts: startTimeISO
            };
            if (idx >= 0) {
              next[idx] = { ...next[idx], ...updated };
            } else {
              next.push(updated);
            }
            return next;
          });
          setAnalysisStates(prev => ({
            ...prev,
            [analysisType]: { content: '', loading: true, error: null }
          }));
          try {
            abortControllerRef.current?.abort();
            abortControllerRef.current = new AbortController();
            const startedMsLocal = Date.now();
            const response = await fetch(
              `/api/financials/${normalizedMarket}/${unifiedSymbol}/analysis/${analysisType}/stream?company_name=${encodeURIComponent(financials?.name || unifiedSymbol)}`,
              { signal: abortControllerRef.current.signal }
            );
            if (!response.ok) {
              throw new Error(`HTTP error! status: ${response.status}`);
            }
            const reader = response.body?.getReader();
            const decoder = new TextDecoder();
            let aggregate = '';
            if (reader) {
              // 持续读取并追加到内容
              while (true) {
                const { value, done } = await reader.read();
                if (done) break;
                const chunk = decoder.decode(value, { stream: true });
                aggregate += chunk;
                const snapshot = aggregate;
                setAnalysisStates(prev => ({
                  ...prev,
                  [analysisType]: {
                    ...prev[analysisType],
                    content: snapshot,
                    loading: true,
                    error: null,
                  }
                }));
              }
            }
            const endTime = new Date().toISOString();
            const elapsedMs = Date.now() - startedMsLocal;
            setAnalysisStates(prev => ({
              ...prev,
              [analysisType]: {
                ...prev[analysisType],
                content: aggregate,
                loading: false,
                error: null,
                elapsed_ms: elapsedMs,
              }
            }));
            setAnalysisRecords(prev => prev.map(record => 
              record.type === analysisType
                ? {
                    ...record,
                    status: 'done',
                    end_ts: endTime,
                    duration_ms: elapsedMs,
                  }
                : record
            ));
          } catch (err) {
            if (err && typeof err === 'object' && (err as any).name === 'AbortError') {
              setAnalysisStates(prev => ({
                ...prev,
                [analysisType]: { content: '', loading: false, error: null }
              }));
              setAnalysisRecords(prev => prev.map(record => 
                record.type === analysisType
                  ? { ...record, status: 'pending', start_ts: undefined }
                  : record
              ));
              analysisFetchedRefs.current[analysisType] = false;
              break;
            }
            const errorMessage = err instanceof Error ? err.message : '加载失败';
            const endTime = new Date().toISOString();
            setAnalysisStates(prev => ({
              ...prev,
              [analysisType]: { 
                content: '', 
                loading: false, 
                error: errorMessage 
              }
            }));
            setAnalysisRecords(prev => prev.map(record => 
              record.type === analysisType
                ? {
                    ...record,
                    status: 'error',
                    end_ts: endTime,
                    error: errorMessage
                  }
                : record
            ));
          } finally {
            setCurrentAnalysisTask(null);
            currentAnalysisTypeRef.current = null;
            analysisFetchedRefs.current[analysisType] = true;
          }
        }
      } finally {
        isAnalysisRunningRef.current = false;
      }
    };
    runAnalysesSequentially();
  }, [isLoading, error, financials, analysisConfig, analysisTypes, normalizedMarket, unifiedSymbol, startTime, manualRunKey]);

  const stopAll = () => {
    stopRequestedRef.current = true;
    abortControllerRef.current?.abort();
    abortControllerRef.current = null;
    isAnalysisRunningRef.current = false;
    if (currentAnalysisTypeRef.current) {
      analysisFetchedRefs.current[currentAnalysisTypeRef.current] = false;
    }
    setCurrentAnalysisTask(null);
    setStartTime(null);
  };

  const continuePending = () => {
    if (isAnalysisRunningRef.current) return;
    stopRequestedRef.current = false;
    setStartTime((prev) => (prev == null ? Date.now() - elapsedSeconds * 1000 : prev));
    setManualRunKey((k) => k + 1);
  };

  const triggerAnalysis = async () => {
      const reqId = await triggerAnalysisRequest(unifiedSymbol, normalizedMarket || '');
      if (reqId) setRequestId(reqId);
  };

  return {
    analysisTypes,
    analysisStates,
    analysisRecords,
    currentAnalysisTask,
    triggerAnalysis,
    triggering,
    requestId,
    setRequestId,
    taskProgress,
    startTime,
    elapsedSeconds,
    completionProgress,
    totalElapsedMs,
    stopAll,
    continuePending,
    retryAnalysis,
    hasRunningTask,
    isAnalysisRunning: isAnalysisRunningRef.current, // 注意：这里返回的是 ref.current，可能不是响应式的。通常需要 state。
    // 但原代码中 isAnalysisRunningRef 仅用于内部逻辑控制，没有直接用于 UI 展示（除了 disabled 状态，但这通常依赖 state 变化触发重渲染）。
    // 在原 UI 中 `disabled={isAnalysisRunningRef.current}` 可能会有问题，如果仅仅 Ref 变了组件不一定会刷新。
    // 不过原代码就是这样写的。
    // 我建议可以用 hasRunningTask 来作为替代。
  };
}

