"use client";

import { useEffect, useMemo, useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { getMnoteRuntimeConfig } from "@/lib/runtime-config";

interface TaskResponse {
  task_id: string;
  status: string;
  progress: number;
  message?: string | null;
}

interface Props {
  documentId: string;
}

export function DocumentTaskPanel({ documentId }: Props) {
  const [task, setTask] = useState<TaskResponse | null>(null);
  const [pending, setPending] = useState(false);
  const runtime = useMemo(() => getMnoteRuntimeConfig(), []);
  const backendUrl = runtime.backendUrl;
  const useConvex = Boolean(runtime.useConvex);

  const triggerTask = async () => {
    // 说明：当前后端（FastAPI）仍使用 Supabase JWT 做鉴权；Convex 迁移阶段先不打通这一块。
    if (useConvex) return;
    if (!backendUrl) return;
    setPending(true);
    try {
      // TODO：如需恢复该能力，请在接入真实鉴权后，将 access_token 从 AuthContext 注入到这里。
      // 这里暂时保持 UI 可渲染，不发起请求。
      void documentId;
    } finally {
      setPending(false);
    }
  };

  useEffect(() => {
    if (useConvex) return;
    if (!backendUrl || !task?.task_id) {
      return;
    }
    const timer = setInterval(async () => {
      // 说明：同上，暂不轮询。
      void timer;
    }, 2000);
    return () => clearInterval(timer);
  }, [backendUrl, task?.task_id, useConvex]);

  return (
    <Card className="mt-4 bg-white shadow-sm">
      <CardContent className="flex items-center justify-between py-3 text-sm text-gray-600">
        <div>
          <div className="font-medium text-gray-900">后端 OCR 流程</div>
          <div className="text-xs text-gray-500">
            状态：{task ? task.status : "未开始"} · 进度：{task ? `${task.progress}%` : "0%"}
          </div>
          {useConvex && (
            <div className="text-xs text-gray-500">
              提示：Convex 迁移阶段暂未接入后端鉴权（Supabase JWT），该按钮仅用于占位。
            </div>
          )}
          {task?.message && <div className="text-xs text-gray-500">提示：{task.message}</div>}
        </div>
        <Button onClick={triggerTask} disabled={pending || useConvex} variant="outline">
          {pending ? "触发中..." : "触发 OCR"}
        </Button>
      </CardContent>
    </Card>
  );
}
