"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import type { VaultDoc } from "@/components/app/document-vault";

interface DocOcrButtonProps {
  doc: VaultDoc;
  onUpdate: (updated: VaultDoc) => void;
}

interface OcrSuccess {
  ok: true;
  extractedText: string;
  model: string;
  tokens?: { input: number; output: number };
}

interface OcrFailure {
  ok: false;
  error: string;
}

type OcrResponse = OcrSuccess | OcrFailure;

export function DocOcrButton({ doc, onUpdate }: DocOcrButtonProps) {
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const hasText = Boolean(doc.extractedText && doc.extractedText.length > 0);

  async function runOcr() {
    if (!doc.inlineData || !doc.inlineMimeType) {
      setError("No inline file data to OCR");
      window.setTimeout(() => setError(null), 5000);
      return;
    }
    setBusy(true);
    setError(null);
    try {
      const resp = await fetch("/api/docs/ocr", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          inlineData: doc.inlineData,
          inlineMimeType: doc.inlineMimeType,
          hint: `Doc type: ${doc.docType}. Filename: ${doc.name}.`,
        }),
      });
      const data = (await resp.json()) as OcrResponse;
      if (!resp.ok || !data.ok) {
        const msg = data.ok === false ? data.error : `OCR failed (${resp.status})`;
        throw new Error(msg);
      }
      onUpdate({
        ...doc,
        extractedText: data.extractedText,
        ocrModel: data.model,
        ocrAt: new Date().toISOString(),
      });
    } catch (e) {
      const msg = e instanceof Error ? e.message : "OCR failed";
      setError(msg);
      window.setTimeout(() => setError(null), 5000);
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="inline-flex flex-col items-end gap-1">
      <Button
        variant="outline"
        size="sm"
        disabled={busy}
        onClick={runOcr}
        title={
          hasText
            ? "Re-run OCR to refresh extracted text"
            : "Run Claude vision OCR to extract document text for search"
        }
      >
        {busy ? (
          <>
            <span className="inline-block animate-spin">{"◠"}</span>
            <span>OCR...</span>
          </>
        ) : hasText ? (
          "Re-OCR"
        ) : (
          "OCR"
        )}
      </Button>
      {error && (
        <span className="text-[10px] text-destructive max-w-[180px] text-right leading-tight">
          {error}
        </span>
      )}
    </div>
  );
}
