'use client';

import { useState } from 'react';
import { OCRUpload } from '@/components/ocr/OCRUpload';
import { OCRResults } from '@/components/ocr/OCRResults';
import { OCRDetail } from '@/components/ocr/OCRDetail';
import { getOCRResult, type OCRResultResponse } from '@/lib/ocr';

export default function OCRPage() {
  const [selectedResult, setSelectedResult] = useState<OCRResultResponse | null>(null);

  const handleUploadComplete = async (resultId: string) => {
    // Refresh results by triggering a re-render
    // The OCRResults component will auto-refresh via its useEffect
    // Optionally fetch the new result
    try {
      const result = await getOCRResult(resultId);
      setSelectedResult(result);
    } catch {
      // Result might not be ready yet, ignore
    }
  };

  const handleSelectResult = (result: OCRResultResponse) => {
    setSelectedResult(result);
  };

  return (
    <div data-testid="ocr-page" className="space-y-6">
      <h1 className="text-2xl font-bold text-text">OCR Erfassung</h1>

      <OCRUpload onUploadComplete={handleUploadComplete} />

      <OCRResults onSelectResult={handleSelectResult} />

      {selectedResult && (
        <OCRDetail
          result={selectedResult}
          onApplyComplete={() => {
            // Could refresh results here
          }}
        />
      )}
    </div>
  );
}
