/**
 * OCR 拍照识账 hook（从旧 transaction/new.tsx 提取，逻辑不变）。
 * 返回 scan()：选图 → OcrProcessor 三级管线 → 解析出账单事件（或 null）。
 */
import { useCallback, useEffect, useRef, useState } from 'react';
import { Alert } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import { getNativeOcrModule, getNativeOcrBridge } from '../services/ocr/ocrBridge';
import { OcrProcessor } from '../domain/pipeline/ocrProcessor';
import { useT } from '../i18n';

export type OcrEvent = NonNullable<Awaited<ReturnType<OcrProcessor['process']>>['event']>;

let processor: OcrProcessor | null = null;

export function useOcrScan() {
  const t = useT();
  const [status, setStatus] = useState('');
  const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  // 组件卸载时清除定时器，避免 setState on unmounted
  useEffect(() => {
    return () => {
      if (timerRef.current) clearTimeout(timerRef.current);
    };
  }, []);

  const scheduleClear = useCallback(() => {
    if (timerRef.current) clearTimeout(timerRef.current);
    timerRef.current = setTimeout(() => setStatus(''), 3000);
  }, []);

  const scan = async (): Promise<OcrEvent | null> => {
    try {
      const result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.Images,
        allowsEditing: false,
        quality: 0.8,
        base64: true,
      });
      if (result.canceled || !result.assets?.[0]?.base64) return null;

      const nativeModule = getNativeOcrModule();
      if (nativeModule && !(await nativeModule.isReady())) {
        Alert.alert(t('ocr.notReady'));
        return null;
      }

      setStatus(t('ocr.scanning'));
      if (!processor) processor = new OcrProcessor(getNativeOcrBridge());
      const ocrResult = await processor.process(result.assets[0].base64);
      setStatus(ocrResult.event ? t('ocr.success') : t('ocr.failed'));
      scheduleClear();
      return ocrResult.event;
    } catch (e) {
      setStatus(t('ocr.failed') + ': ' + (e instanceof Error ? e.message : String(e)));
      scheduleClear();
      return null;
    }
  };

  return { scan, status };
}
