"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)" },
};

export function ProcessPanel() {
  const [processes, setProcesses] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [expanded, setExpanded] = useState<string | null>(null);
  const [detail, setDetail] = useState<any>(null);

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

  const loadDetail = async (uid: string) => {
    if (expanded === uid) {
      setExpanded(null);
      setDetail(null);
      return;
    }
    setExpanded(uid);
    const res = await fetch(`/api/process/${encodeURIComponent(uid)}`);
    const data = await res.json();
    setDetail(data);
  };

  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)" }}>Execution Flows</h2>
        <span
          className="px-2 py-0.5 rounded-full text-[10px] font-medium"
          style={{ background: "var(--cyan-dim)", color: "var(--cyan)" }}
        >
          {processes.length}
        </span>
      </div>
      <div className="space-y-2">
        {processes.map((proc, i) => {
          const isOpen = expanded === proc.uid;

          return (
            <div
              key={i}
              className="rounded-xl border overflow-hidden"
              style={{
                borderColor: isOpen ? "rgba(6,182,212,0.3)" : "var(--border)",
                background: "var(--surface)",
              }}
            >
              <button
                className="w-full text-left flex justify-between items-center p-4 hover:opacity-90"
                onClick={() => loadDetail(proc.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">{proc.name}</span>
                    <span className="ml-2 text-[10px] mono" style={{ color: "var(--text-muted)" }}>
                      {proc.entry_file}
                    </span>
                  </div>
                </div>
                <div className="flex gap-2">
                  <span
                    className="text-[10px] px-2 py-0.5 rounded-full mono"
                    style={{ background: "var(--surface-2)", color: "var(--text-dim)" }}
                  >
                    depth {proc.depth || "?"}
                  </span>
                  <span
                    className="text-[10px] px-2 py-0.5 rounded-full mono"
                    style={{ background: "var(--surface-2)", color: "var(--text-dim)" }}
                  >
                    {proc.steps || proc.symbol_count || "?"} steps
                  </span>
                </div>
              </button>

              {isOpen && detail?.steps && (
                <div className="px-4 pb-4 fade-in">
                  <div className="h-px mb-3" style={{ background: "var(--border)" }} />
                  <div className="space-y-0.5">
                    {detail.steps.map((step: any, j: number) => {
                      const style = TYPE_STYLES[step.type] || TYPE_STYLES.Function;
                      return (
                        <div
                          key={j}
                          className="flex items-center gap-2 text-xs py-1.5 px-2 rounded"
                          style={{ marginLeft: `${step.depth * 16}px` }}
                        >
                          <div
                            className="w-1.5 h-1.5 rounded-full shrink-0"
                            style={{ background: style.color }}
                          />
                          <span
                            className="px-1.5 py-0.5 rounded text-[9px] font-medium mono shrink-0"
                            style={{ color: style.color, background: style.bg }}
                          >
                            {step.type}
                          </span>
                          <span className="mono font-medium">{step.name}</span>
                          <span className="mono text-[10px] ml-auto" style={{ color: "var(--text-muted)" }}>
                            {step.file}:{step.line}
                          </span>
                        </div>
                      );
                    })}
                  </div>
                </div>
              )}

              {isOpen && detail?.step_symbols && !detail?.steps && (
                <div className="px-4 pb-4 fade-in">
                  <div className="h-px mb-3" style={{ background: "var(--border)" }} />
                  <div className="space-y-1">
                    {detail.step_symbols.map((step: any, j: number) => {
                      const style = TYPE_STYLES[step.type] || TYPE_STYLES.Function;
                      return (
                        <div key={j} className="flex items-center gap-2 text-xs py-1">
                          <span
                            className="px-1.5 py-0.5 rounded text-[9px] font-medium mono"
                            style={{ color: style.color, background: style.bg }}
                          >
                            {step.type}
                          </span>
                          <span className="mono">{step.name}</span>
                          <span className="mono text-[10px]" style={{ color: "var(--text-muted)" }}>
                            {step.file}
                          </span>
                        </div>
                      );
                    })}
                  </div>
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}
