import { useState, useCallback } from 'react';
import { transformCategoryStream } from '../services/api';
import type {
  TransformationInput,
  TransformationProgress,
  TransformationCategoryResult,
  TransformationDAGResult,
  CategoryDefinition,
} from '../types';

interface UseTransformationOptions {
  model?: string;
  temperature?: number;
  keywordCount?: number;
}

export function useTransformation(options: UseTransformationOptions = {}) {
  const [loading, setLoading] = useState(false);
  const [progress, setProgress] = useState<TransformationProgress>({
    step: 'idle',
    currentCategory: '',
    processedCategories: [],
    message: '',
  });
  const [results, setResults] = useState<TransformationDAGResult | null>(null);
  const [error, setError] = useState<string | null>(null);

  const transformCategory = useCallback(
    async (
      query: string,
      category: CategoryDefinition,
      attributes: string[]
    ): Promise<TransformationCategoryResult | null> => {
      return new Promise((resolve) => {
        setProgress((prev) => ({
          ...prev,
          step: 'keyword',
          currentCategory: category.name,
          message: `為「${category.name}」生成新關鍵字...`,
        }));

        transformCategoryStream(
          {
            query,
            category: category.name,
            attributes,
            model: options.model,
            temperature: options.temperature,
            keyword_count: options.keywordCount || 3,
          },
          {
            onKeywordStart: () => {
              setProgress((prev) => ({
                ...prev,
                step: 'keyword',
                message: `為「${category.name}」生成新關鍵字...`,
              }));
            },
            onKeywordComplete: (keywords) => {
              setProgress((prev) => ({
                ...prev,
                message: `生成了 ${keywords.length} 個新關鍵字`,
              }));
            },
            onDescriptionStart: () => {
              setProgress((prev) => ({
                ...prev,
                step: 'description',
                message: `為「${category.name}」生成創新描述...`,
              }));
            },
            onDescriptionComplete: (count) => {
              setProgress((prev) => ({
                ...prev,
                message: `生成了 ${count} 個創新描述`,
              }));
            },
            onDone: (result) => {
              setProgress((prev) => ({
                ...prev,
                step: 'done',
                processedCategories: [...prev.processedCategories, category.name],
                message: `「${category.name}」處理完成`,
              }));
              resolve(result);
            },
            onError: (err) => {
              setProgress((prev) => ({
                ...prev,
                step: 'error',
                error: err,
                message: `處理「${category.name}」時發生錯誤`,
              }));
              resolve(null);
            },
          }
        ).catch((err) => {
          setProgress((prev) => ({
            ...prev,
            step: 'error',
            error: err.message,
            message: `處理「${category.name}」時發生錯誤`,
          }));
          resolve(null);
        });
      });
    },
    [options.model, options.temperature, options.keywordCount]
  );

  const transformAll = useCallback(
    async (input: TransformationInput) => {
      setLoading(true);
      setError(null);
      setResults(null);
      setProgress({
        step: 'idle',
        currentCategory: '',
        processedCategories: [],
        message: '開始處理...',
      });

      const categoryResults: TransformationCategoryResult[] = [];

      // Process each category sequentially
      for (const category of input.categories) {
        const attributes = input.attributesByCategory[category.name] || [];
        if (attributes.length === 0) continue;

        const result = await transformCategory(input.query, category, attributes);
        if (result) {
          categoryResults.push(result);
        }
      }

      // Build final result
      const finalResult: TransformationDAGResult = {
        query: input.query,
        results: categoryResults,
      };

      setResults(finalResult);
      setLoading(false);
      setProgress((prev) => ({
        ...prev,
        step: 'done',
        message: '所有類別處理完成',
      }));

      return finalResult;
    },
    [transformCategory]
  );

  const clearResults = useCallback(() => {
    setResults(null);
    setError(null);
    setProgress({
      step: 'idle',
      currentCategory: '',
      processedCategories: [],
      message: '',
    });
  }, []);

  return {
    loading,
    progress,
    results,
    error,
    transformCategory,
    transformAll,
    clearResults,
  };
}
