import { useState } from "react";
import ModelInputBar from "./components/ModelInputBar";
import ModelLayersCard from "./components/ModelLayersCard";
import ModelInfo from "./components/ModelInfo";
import LoadingSpinner from "./assets/loading";

export default function App() {
  const [structure, setStructure] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  const fetchModelStructure = async (modelName, selectedOption) => {
    if (!modelName) return;
    setLoading(true);
    setError("");
    setStructure(null);

    try {
        // append options as query params when provided
        const params = new URLSearchParams({ name: modelName });
        if (selectedOption && selectedOption !== "none") {
          params.append("model_type", selectedOption);
        }

        const res = await fetch(`/api/model?${params.toString()}`);
        if (!res.ok) {
            throw new Error(`Error: ${res.status}`);
        }
        const data = await res.json();
         console.log("data: ", data)
        setStructure(data?.data);
    } catch (err) {
        console.log('err: ', err)
        setError("Failed to fetch model structure. Please check the model name.");
    } finally {
        setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-100 to-slate-200 flex flex-col items-center p-6">
      <div className="w-full max-w-3xl bg-white rounded-2xl shadow-lg p-6">
        {/* Header */}
        <h1 className="text-3xl font-bold text-center text-slate-800 mb-4">
          Transformer Model Structure Viewer
        </h1>
        <p className="text-center text-slate-500 mb-6">
          Enter a model name (e.g. <code>deepseek-ai/DeepSeek-V3.1</code>) to view its
          architecture.
        </p>

        {/* Input Bar */}
        <ModelInputBar
          loading={loading}
          fetchModelStructure={fetchModelStructure}
        />
        {error && (
          <div className="text-red-600 text-center font-medium mb-4">{error}</div>
        )}

      {/* Model Info */}
      {structure && (
        <ModelInfo structure={
          Object.fromEntries(
            Object.entries(structure).filter(([key]) => key !== "layers")
          )
        } />
      )}
      </div>
      {loading && <LoadingSpinner />}

      {/* Model Layers */}
      {structure && (
        <ModelLayersCard name={structure?.layers?.class_name} layers={structure?.layers?.children || {}} />
      )}

      {/* Footer */}
      <footer className="mt-8 text-slate-500 text-sm text-center">
        This app is currently running on free CPU and thus does not support models that use flash_attn. If you have GPU resources available, consider using a local setup for better performance by following the instructions in the <a href="https://huggingface.co/spaces/maomao88/model_structure_viewer/blob/main/README.md" className="text-sky-600 underline">README</a>.
      </footer>
    </div>
  );
}
