import { useState, useCallback } from 'react';
import { deduplicateDescriptions } from '../services/api';
import type {
  ExpertTransformationDescription,
  DeduplicationResult,
  DeduplicationProgress,
  DeduplicationMethod,
  PromptLanguage,
} from '../types';

/**
 * Hook for managing deduplication state and operations
 */
export function useDeduplication() {
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState<DeduplicationResult | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [progress, setProgress] = useState<DeduplicationProgress>({
    step: 'idle',
    message: '',
  });

  /**
   * Execute deduplication on a list of descriptions
   *
   * @param descriptions - List of descriptions to deduplicate
   * @param threshold - Similarity threshold (only used for embedding method)
   * @param method - Deduplication method: 'embedding' (fast) or 'llm' (accurate but slow)
   * @param lang - Prompt language for LLM method
   */
  const deduplicate = useCallback(async (
    descriptions: ExpertTransformationDescription[],
    threshold: number = 0.85,
    method: DeduplicationMethod = 'embedding',
    lang: PromptLanguage = 'zh'
  ) => {
    if (!descriptions || descriptions.length === 0) {
      setError(lang === 'zh' ? '沒有可去重的描述' : 'No descriptions to deduplicate');
      return;
    }

    setLoading(true);
    setError(null);
    setResult(null);

    const methodLabel = method === 'embedding' ? 'Embedding' : 'LLM';
    const pairCount = (descriptions.length * (descriptions.length - 1)) / 2;
    const progressMessage = method === 'llm'
      ? (lang === 'zh'
        ? `正在使用 LLM 處理 ${descriptions.length} 個描述（${pairCount} 次比較）...`
        : `Processing ${descriptions.length} descriptions with LLM (${pairCount} comparisons)...`)
      : (lang === 'zh'
        ? `正在使用 ${methodLabel} 處理 ${descriptions.length} 個描述...`
        : `Processing ${descriptions.length} descriptions with ${methodLabel}...`);

    setProgress({
      step: 'processing',
      message: progressMessage,
    });

    try {
      const deduplicationResult = await deduplicateDescriptions({
        descriptions,
        similarity_threshold: threshold,
        method,
        lang,
      });

      setResult(deduplicationResult);
      setProgress({
        step: 'done',
        message: lang === 'zh'
          ? `發現 ${deduplicationResult.total_groups} 個獨特群組，${deduplicationResult.total_duplicates} 個重複（${methodLabel}）`
          : `Found ${deduplicationResult.total_groups} unique groups, ${deduplicationResult.total_duplicates} duplicates (${methodLabel})`,
      });
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Unknown error';
      setError(errorMessage);
      setProgress({
        step: 'error',
        message: lang === 'zh' ? '去重失敗' : 'Deduplication failed',
        error: errorMessage,
      });
    } finally {
      setLoading(false);
    }
  }, []);

  /**
   * Clear results and reset state
   */
  const clearResult = useCallback(() => {
    setResult(null);
    setError(null);
    setProgress({
      step: 'idle',
      message: '',
    });
  }, []);

  return {
    loading,
    result,
    error,
    progress,
    deduplicate,
    clearResult,
  };
}
