"use client";

import { useEffect, useState } from "react";

const TYPE_STYLES: Record<string, { color: string; bg: string }> = {
  Function: { color: "var(--accent)", bg: "var(--accent-glow)" },
  Class: { color: "var(--green)", bg: "var(--green-dim)" },
  Method: { color: "var(--yellow)", bg: "var(--yellow-dim)" },
};

interface Props {
  onSelectSymbol: (uid: string) => void;
}

export function ClusterPanel({ onSelectSymbol }: Props) {
  const [clusters, setClusters] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [expanded, setExpanded] = useState<string | null>(null);

  useEffect(() => {
    fetch("/api/clusters")
      .then((r) => r.json())
      .then((data) => {
        setClusters(data.clusters || []);
        setLoading(false);
      })
      .catch(() => setLoading(false));
  }, []);

  if (loading) {
    return (
      <div className="p-6 space-y-3">
        {[1, 2, 3, 4].map((i) => (
          <div key={i} className="h-16 rounded-xl pulse-glow" style={{ background: "var(--surface)" }} />
        ))}
      </div>
    );
  }

  return (
    <div className="p-6 overflow-y-auto h-full">
      <div className="flex items-center gap-3 mb-5">
        <h2 className="text-sm font-bold" style={{ color: "var(--text)" }}>Functional Clusters</h2>
        <span
          className="px-2 py-0.5 rounded-full text-[10px] font-medium"
          style={{ background: "var(--accent-glow)", color: "var(--accent)" }}
        >
          {clusters.length}
        </span>
      </div>
      <div className="space-y-2">
        {clusters.map((cluster, i) => {
          const members = cluster.members || [];
          const isOpen = expanded === cluster.uid;

          return (
            <div
              key={i}
              className="rounded-xl border overflow-hidden"
              style={{
                borderColor: isOpen ? "rgba(99,102,241,0.3)" : "var(--border)",
                background: "var(--surface)",
              }}
            >
              <button
                className="w-full text-left flex justify-between items-center p-4 hover:opacity-90"
                onClick={() => setExpanded(isOpen ? null : cluster.uid)}
              >
                <div className="flex items-center gap-3">
                  <span
                    className="text-xs transition-transform"
                    style={{ color: "var(--text-dim)", transform: isOpen ? "rotate(90deg)" : "none" }}
                  >
                    ▶
                  </span>
                  <div>
                    <span className="font-semibold text-sm">{cluster.name}</span>
                    <span className="ml-2 text-[10px]" style={{ color: "var(--text-muted)" }}>
                      {members.length} symbols
                    </span>
                  </div>
                </div>
                <CohesionBadge value={cluster.cohesion} />
              </button>

              {isOpen && (
                <div className="px-4 pb-3 space-y-0.5 fade-in">
                  <div className="h-px mb-2" style={{ background: "var(--border)" }} />
                  {members.map((m: any, j: number) => {
                    const style = TYPE_STYLES[m.type] || TYPE_STYLES.Function;
                    return (
                      <button
                        key={j}
                        className="w-full text-left text-xs px-3 py-1.5 rounded-lg flex items-center gap-2 hover:opacity-80"
                        style={{ background: "var(--bg)" }}
                        onClick={() => onSelectSymbol(m.uid)}
                      >
                        <span
                          className="px-1.5 py-0.5 rounded text-[9px] font-medium mono shrink-0"
                          style={{ color: style.color, background: style.bg }}
                        >
                          {m.type}
                        </span>
                        <span className="mono font-medium">{m.name}</span>
                        <span className="ml-auto text-[10px] truncate max-w-[200px]" style={{ color: "var(--text-muted)" }}>
                          {m.file}
                        </span>
                      </button>
                    );
                  })}
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

function CohesionBadge({ value }: { value: number }) {
  const pct = (value * 100).toFixed(0);
  const color = value >= 0.7 ? "var(--green)" : value >= 0.3 ? "var(--yellow)" : "var(--red)";
  const bg = value >= 0.7 ? "var(--green-dim)" : value >= 0.3 ? "var(--yellow-dim)" : "var(--red-dim)";

  return (
    <span
      className="text-[10px] font-medium px-2 py-0.5 rounded-full mono"
      style={{ background: bg, color }}
    >
      {pct}%
    </span>
  );
}
