import { useState, useEffect } from "react";
import axios from "axios";
import { Header } from "./components/Header";
import { Sidebar } from "./components/Sidebar";
import { UploadSection } from "./components/UploadSection";
import { ResultsPanel } from "./components/ResultsPanel";
import { Footer } from "./components/Footer";
import { ProgressBar } from "./components/progressbar";

export function App() {
const [selectedTest, setSelectedTest] = useState("cytology");
const [uploadedImage, setUploadedImage] = useState<string | null>(null);
const [selectedModel, setSelectedModel] = useState("");
const [apiResult, setApiResult] = useState<any>(null);
const [showResults, setShowResults] = useState(false);
const [currentStep, setCurrentStep] = useState(0);
const [loading, setLoading] = useState(false);

// Progress bar logic
useEffect(() => {
if (showResults) setCurrentStep(2);
else if (uploadedImage) setCurrentStep(1);
else setCurrentStep(0);
}, [uploadedImage, showResults]);

// Reset logic
useEffect(() => {
setCurrentStep(0);
setShowResults(false);
setUploadedImage(null);
setSelectedModel("");
setApiResult(null);
}, [selectedTest]);

  const handleAnalyze = async () => {
    console.log('Analyze button clicked', { uploadedImage, selectedModel });
    if (!uploadedImage || !selectedModel) {
      alert("Please select a model and upload an image first!");
      return;
    }

    setLoading(true);
    setShowResults(false);
    setApiResult(null);

    try {
      // Extract file extension from data URL or use .jpg default
      const extension = uploadedImage.startsWith('data:image/')
        ? uploadedImage.split(';')[0].split('/')[1]
        : 'jpg';
      
      // Create a more descriptive filename
      const filename = `analysis_input.${extension}`;
      
      let blob: Blob;
      if (uploadedImage.startsWith('data:')) {
        // Handle data URLs (from file upload)
        blob = await fetch(uploadedImage).then(r => r.blob());
      } else {
        // Handle sample images (relative URLs)
        blob = await fetch(uploadedImage)
          .then(r => r.blob())
          .catch(() => {
            // If fetch fails, try with base URL
            const baseURL = import.meta.env.MODE === "development"
              ? "http://127.0.0.1:5173"
              : window.location.origin;
            return fetch(`${baseURL}${uploadedImage}`).then(r => r.blob());
          });
      }

      const file = new File([blob], filename, { type: blob.type || `image/${extension}` });
      const formData = new FormData();
      formData.append("file", file);
      formData.append("model_name", selectedModel);

      console.log('Sending request:', {
        filename,
        type: file.type,
        size: file.size,
        model: selectedModel
      });

      const baseURL = import.meta.env.MODE === "development"
        ? "http://127.0.0.1:8000"
        : window.location.origin;

      const res = await axios.post(`${baseURL}/predict/`, formData, {
        headers: { "Content-Type": "multipart/form-data" },
      });

      if (res.data.error) {
        throw new Error(res.data.error);
      }

      console.log('Received response:', res.data);
      setApiResult(res.data);
      setShowResults(true);
    } catch (err: any) {
      console.error("❌ Error during inference:", err);
      const errorMessage = err.response?.data?.error || err.message || "Unknown error occurred";
      alert(`Error analyzing the image: ${errorMessage}`);
    } finally {
      setLoading(false);
    }
};

return ( <div className="flex flex-col min-h-screen w-full bg-gray-50"> <Header /> <ProgressBar currentStep={currentStep} />


  <div className="flex flex-1">
    <Sidebar selectedTest={selectedTest} onTestChange={setSelectedTest} />

    <main className="flex-1 p-6">
      <div className="max-w-7xl mx-auto grid grid-cols-1 lg:grid-cols-2 gap-6">
        <UploadSection
          selectedTest={selectedTest}
          uploadedImage={uploadedImage}
          setUploadedImage={setUploadedImage}
          selectedModel={selectedModel}
          setSelectedModel={setSelectedModel}
          onAnalyze={handleAnalyze}
        />

        {(showResults || loading) && (
          <ResultsPanel
            uploadedImage={
              apiResult?.annotated_image_url || uploadedImage
            }
            result={apiResult}
            loading={loading}
          />
        )}
      </div>
    </main>
  </div>

  <Footer />
</div>


);
}
