"use client";

import { useEffect, useState } from "react";
import { GraphViewer } from "@/components/GraphViewer";
import { SearchBar } from "@/components/SearchBar";
import { SymbolDetail } from "@/components/SymbolDetail";
import { StatsPanel } from "@/components/StatsPanel";
import { ClusterPanel } from "@/components/ClusterPanel";
import { ProcessPanel } from "@/components/ProcessPanel";

type Tab = "graph" | "clusters" | "processes";

const TAB_CONFIG: { key: Tab; label: string; icon: string }[] = [
  { key: "graph", label: "Graph", icon: "⬡" },
  { key: "clusters", label: "Clusters", icon: "◎" },
  { key: "processes", label: "Flows", icon: "⇢" },
];

export default function Home() {
  const [selectedUid, setSelectedUid] = useState<string | null>(null);
  const [activeTab, setActiveTab] = useState<Tab>("graph");
  const [stats, setStats] = useState<any>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    fetch("/api/stats")
      .then((r) => {
        if (!r.ok) throw new Error("Backend not running");
        return r.json();
      })
      .then(setStats)
      .catch(() => setError("Cannot connect to backend. Run: codegraph serve"));
  }, []);

  if (error) {
    return (
      <div className="flex items-center justify-center h-screen">
        <div className="text-center p-10 rounded-2xl fade-in" style={{ background: "var(--surface)", boxShadow: "var(--shadow-lg)" }}>
          <div className="text-4xl mb-4">⚠</div>
          <h2 className="text-lg font-semibold mb-2" style={{ color: "var(--red)" }}>Connection Error</h2>
          <p className="text-sm mb-6" style={{ color: "var(--text-dim)" }}>{error}</p>
          <code className="mono block p-4 rounded-lg text-xs" style={{ background: "var(--bg)", color: "var(--accent)" }}>
            codegraph serve ./your-project
          </code>
        </div>
      </div>
    );
  }

  return (
    <div className="h-screen flex flex-col" style={{ background: "var(--bg)" }}>
      {/* Header */}
      <header
        className="flex items-center justify-between px-6 py-3 border-b"
        style={{ borderColor: "var(--border)", background: "var(--surface)" }}
      >
        <div className="flex items-center gap-5">
          <div className="flex items-center gap-2.5">
            <div
              className="w-8 h-8 rounded-lg flex items-center justify-center text-sm font-bold"
              style={{ background: "var(--gradient-accent)", color: "#fff" }}
            >
              CG
            </div>
            <div>
              <h1 className="text-sm font-bold tracking-tight" style={{ color: "var(--text)" }}>
                CodeGraph
              </h1>
              <p className="text-[10px]" style={{ color: "var(--text-muted)" }}>
                Intelligence Engine
              </p>
            </div>
          </div>
          <div className="h-6 w-px" style={{ background: "var(--border)" }} />
          <StatsPanel stats={stats} />
        </div>
        <SearchBar onSelect={setSelectedUid} />
      </header>

      {/* Tabs */}
      <nav
        className="flex items-center gap-1 px-6 py-1.5 border-b"
        style={{ borderColor: "var(--border)", background: "var(--surface)" }}
      >
        {TAB_CONFIG.map(({ key, label, icon }) => (
          <button
            key={key}
            onClick={() => setActiveTab(key)}
            className="flex items-center gap-1.5 px-4 py-1.5 rounded-lg text-xs font-medium"
            style={{
              background: activeTab === key ? "var(--accent-glow)" : "transparent",
              color: activeTab === key ? "var(--accent)" : "var(--text-dim)",
              border: activeTab === key ? "1px solid rgba(99,102,241,0.3)" : "1px solid transparent",
            }}
          >
            <span className="text-sm">{icon}</span>
            {label}
          </button>
        ))}
      </nav>

      {/* Main content */}
      <div className="flex-1 flex overflow-hidden">
        {/* Left: Visualization */}
        <div className="flex-1 relative">
          {activeTab === "graph" && <GraphViewer onSelectNode={setSelectedUid} />}
          {activeTab === "clusters" && <ClusterPanel onSelectSymbol={setSelectedUid} />}
          {activeTab === "processes" && <ProcessPanel />}
        </div>

        {/* Right: Detail panel */}
        {selectedUid && (
          <div
            className="w-[420px] border-l overflow-y-auto slide-in-right"
            style={{ borderColor: "var(--border)", background: "var(--surface)" }}
          >
            <div
              className="flex justify-between items-center px-5 py-3 border-b sticky top-0 z-10"
              style={{ borderColor: "var(--border)", background: "var(--surface)" }}
            >
              <h3 className="text-xs font-semibold uppercase tracking-wider" style={{ color: "var(--text-dim)" }}>
                Symbol Detail
              </h3>
              <button
                onClick={() => setSelectedUid(null)}
                className="w-6 h-6 rounded flex items-center justify-center text-xs hover:opacity-80"
                style={{ color: "var(--text-dim)", background: "var(--surface-2)" }}
              >
                ✕
              </button>
            </div>
            <div className="p-5">
              <SymbolDetail uid={selectedUid} />
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
