import { useState, useCallback } from 'react';
import type {
  AttributeDAG,
  DAGStreamAnalyzeResponse,
  PathId,
  PathState,
  DualPathState,
  DAGProgress,
  CategoryMode,
  PromptLanguage,
} from '../types';
import { CategoryMode as CategoryModeValues } from '../types';
import { analyzeAttributesStream } from '../services/api';

const initialProgress: DAGProgress = {
  step: 'idle',
  message: '',
};

const initialPathState: PathState = {
  query: '',
  result: null,
  loading: false,
  progress: initialProgress,
  error: null,
};

export interface AnalyzeOptions {
  model?: string;
  temperature?: number;
  chainCount?: number;
  categoryMode?: CategoryMode;
  customCategories?: string[];
  suggestedCategoryCount?: number;
  lang?: PromptLanguage;
}

export function useDualPathAttribute() {
  const [state, setState] = useState<DualPathState>({
    pathA: { ...initialPathState },
    pathB: { ...initialPathState },
  });

  const getPathKey = (pathId: PathId): 'pathA' | 'pathB' =>
    pathId === 'A' ? 'pathA' : 'pathB';

  const updatePathState = useCallback((
    pathId: PathId,
    updates: Partial<PathState>
  ) => {
    const pathKey = getPathKey(pathId);
    setState(prev => ({
      ...prev,
      [pathKey]: {
        ...prev[pathKey],
        ...updates,
      },
    }));
  }, []);

  const updatePathProgress = useCallback((
    pathId: PathId,
    step: DAGProgress['step'],
    message: string,
    error?: string
  ) => {
    updatePathState(pathId, {
      progress: { step, message, error },
    });
  }, [updatePathState]);

  const analyzePath = useCallback(async (
    pathId: PathId,
    query: string,
    options: AnalyzeOptions = {}
  ) => {
    const {
      model,
      temperature,
      chainCount = 5,
      categoryMode = CategoryModeValues.DYNAMIC_AUTO,
      customCategories,
      suggestedCategoryCount = 3,
      lang = 'zh',
    } = options;

    // Reset state for this path
    updatePathState(pathId, {
      query,
      result: null,
      loading: true,
      error: null,
      progress: { step: 'idle', message: lang === 'zh' ? '準備分析中...' : 'Preparing analysis...' },
    });

    try {
      await analyzeAttributesStream(
        {
          query,
          chain_count: chainCount,
          model,
          temperature,
          category_mode: categoryMode,
          custom_categories: customCategories,
          suggested_category_count: suggestedCategoryCount,
          lang,
        },
        {
          onStep0Start: () => {
            updatePathProgress(pathId, 'step0', lang === 'zh' ? '正在分析類別...' : 'Analyzing categories...');
          },

          onStep0Complete: () => {
            updatePathProgress(pathId, 'step0', lang === 'zh' ? '類別分析完成' : 'Categories analyzed');
          },

          onCategoriesResolved: (categories) => {
            updatePathProgress(pathId, 'step0', lang === 'zh' ? `使用 ${categories.length} 個類別` : `Using ${categories.length} categories`);
          },

          onStep1Start: () => {
            updatePathProgress(pathId, 'step1', lang === 'zh' ? '正在分析屬性...' : 'Analyzing attributes...');
          },

          onStep1Complete: () => {
            updatePathProgress(pathId, 'step1', lang === 'zh' ? '屬性分析完成' : 'Attributes analyzed');
          },

          onRelationshipsStart: () => {
            updatePathProgress(pathId, 'relationships', lang === 'zh' ? '正在生成關係...' : 'Generating relationships...');
          },

          onRelationshipsComplete: (count) => {
            updatePathProgress(pathId, 'relationships', lang === 'zh' ? `生成 ${count} 個關係` : `Generated ${count} relationships`);
          },

          onDone: (response: DAGStreamAnalyzeResponse) => {
            updatePathState(pathId, {
              result: response.dag,
              loading: false,
              progress: { step: 'done', message: lang === 'zh' ? '分析完成！' : 'Analysis complete!' },
            });
          },

          onError: (errorMsg) => {
            updatePathState(pathId, {
              loading: false,
              error: errorMsg,
              progress: { step: 'error', message: lang === 'zh' ? `錯誤: ${errorMsg}` : `Error: ${errorMsg}`, error: errorMsg },
            });
          },
        }
      );
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Unknown error';
      updatePathState(pathId, {
        loading: false,
        error: errorMessage,
        progress: { step: 'error', message: lang === 'zh' ? `錯誤: ${errorMessage}` : `Error: ${errorMessage}`, error: errorMessage },
      });
    }
  }, [updatePathState, updatePathProgress]);

  const analyzeParallel = useCallback(async (
    queryA: string,
    queryB: string,
    options: AnalyzeOptions = {}
  ) => {
    // Run both analyses in parallel
    await Promise.all([
      analyzePath('A', queryA, options),
      analyzePath('B', queryB, options),
    ]);
  }, [analyzePath]);

  const clearPath = useCallback((pathId: PathId) => {
    updatePathState(pathId, { ...initialPathState });
  }, [updatePathState]);

  const clearAll = useCallback(() => {
    setState({
      pathA: { ...initialPathState },
      pathB: { ...initialPathState },
    });
  }, []);

  const setPathResult = useCallback((pathId: PathId, result: AttributeDAG) => {
    updatePathState(pathId, {
      result,
      loading: false,
      progress: { step: 'done', message: 'Loaded from history' },
    });
  }, [updatePathState]);

  // Computed properties
  const pathA = state.pathA;
  const pathB = state.pathB;
  const bothLoading = pathA.loading && pathB.loading;
  const anyLoading = pathA.loading || pathB.loading;
  const bothComplete = pathA.result !== null && pathB.result !== null;
  const bothIdle = pathA.progress.step === 'idle' && pathB.progress.step === 'idle';

  return {
    state,
    pathA,
    pathB,
    analyzePath,
    analyzeParallel,
    clearPath,
    clearAll,
    setPathResult,
    // Status flags
    bothLoading,
    anyLoading,
    bothComplete,
    bothIdle,
  };
}
