import { useState, useCallback } from 'react';
import type {
  AttributeDAG,
  DAGStreamAnalyzeResponse,
  PromptLanguage
} from '../types';
import { CategoryMode } from '../types';
import { analyzeAttributesStream } from '../services/api';

interface DAGProgress {
  step: 'idle' | 'step0' | 'step1' | 'relationships' | 'done' | 'error';
  message: string;
  error?: string;
}

interface DAGHistoryItem {
  query: string;
  result: AttributeDAG;
  timestamp: Date;
}

export function useAttribute() {
  const [progress, setProgress] = useState<DAGProgress>({
    step: 'idle',
    message: '',
  });
  const [error, setError] = useState<string | null>(null);
  const [currentResult, setCurrentResult] = useState<AttributeDAG | null>(null);
  const [history, setHistory] = useState<DAGHistoryItem[]>([]);

  const analyze = useCallback(async (
    query: string,
    model?: string,
    temperature?: number,
    chainCount: number = 5,
    categoryMode: CategoryMode = CategoryMode.DYNAMIC_AUTO,
    customCategories?: string[],
    suggestedCategoryCount: number = 3,
    lang: PromptLanguage = 'zh'
  ) => {
    // Reset state
    setProgress({
      step: 'idle',
      message: lang === 'zh' ? '準備開始分析...' : 'Preparing analysis...',
    });
    setError(null);
    setCurrentResult(null);

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

          onStep0Complete: () => {
            setProgress(prev => ({
              ...prev,
              message: lang === 'zh' ? '類別分析完成' : 'Category analysis complete',
            }));
          },

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

          onStep1Start: () => {
            setProgress({
              step: 'step1',
              message: lang === 'zh' ? '正在分析物件屬性列表...' : 'Analyzing object attributes...',
            });
          },

          onStep1Complete: () => {
            setProgress(prev => ({
              ...prev,
              message: lang === 'zh' ? '屬性列表分析完成' : 'Attribute analysis complete',
            }));
          },

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

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

          onDone: (response: DAGStreamAnalyzeResponse) => {
            setProgress({
              step: 'done',
              message: lang === 'zh' ? '分析完成！' : 'Analysis complete!',
            });
            setCurrentResult(response.dag);

            setHistory((prev) => [
              {
                query,
                result: response.dag,
                timestamp: new Date(),
              },
              ...prev,
            ]);
          },

          onError: (errorMsg) => {
            setProgress({
              step: 'error',
              error: errorMsg,
              message: lang === 'zh' ? `錯誤: ${errorMsg}` : `Error: ${errorMsg}`,
            });
            setError(errorMsg);
          },
        }
      );
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Unknown error';
      setProgress({
        step: 'error',
        error: errorMessage,
        message: lang === 'zh' ? `錯誤: ${errorMessage}` : `Error: ${errorMessage}`,
      });
      setError(errorMessage);
      throw err;
    }
  }, []);

  const loadFromHistory = useCallback((item: DAGHistoryItem, lang: PromptLanguage = 'zh') => {
    setCurrentResult(item.result);
    setError(null);
    setProgress({
      step: 'done',
      message: lang === 'zh' ? '從歷史記錄載入' : 'Loaded from history',
    });
  }, []);

  const clearResult = useCallback(() => {
    setCurrentResult(null);
    setError(null);
    setProgress({
      step: 'idle',
      message: '',
    });
  }, []);

  const isLoading = progress.step === 'step0' || progress.step === 'step1' || progress.step === 'relationships';

  return {
    loading: isLoading,
    progress,
    error,
    currentResult,
    history,
    analyze,
    loadFromHistory,
    clearResult,
  };
}
