import React, { useState } from "react";
import ChatInterface from "./components/ChatInterface";

const API_BASE_URL = process.env.REACT_APP_API_BASE_URL || "";

console.log("API_BASE_URL:", API_BASE_URL);

const App: React.FC = () => {
  const [pipelineId, setPipelineId] = useState<string | null>(null);

  const handleFileUpload = async (file: File) => {
    const formData = new FormData();
    formData.append("file", file);

    const url = `${API_BASE_URL}/api/upload`;
    console.log("Uploading file to:", url);

    try {
      const response = await fetch(url, {
        method: "POST",
        body: formData,
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.detail || "Upload failed");
      }

      const data = await response.json();
      console.log("Upload response:", data);
      setPipelineId(data.pipeline_id);
    } catch (error) {
      console.error("Error uploading file:", error);
      throw error;
    }
  };

  return (
    <div className="min-h-screen bg-gray-900">
      <header className="bg-gray-800 border-b border-gray-700">
        <div className="max-w-7xl mx-auto py-4 px-4">
          <h1 className="text-2xl font-bold text-white">Document Q&A Chat</h1>
        </div>
      </header>
      <main className="max-w-7xl mx-auto">
        <ChatInterface
          pipelineId={pipelineId}
          onFileUpload={handleFileUpload}
        />
      </main>
    </div>
  );
};

export default App;
