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

const REL_COLORS: Record<string, string> = {
  CALLS: "var(--accent)",
  IMPORTS: "var(--green)",
  EXTENDS: "var(--red)",
  HAS_METHOD: "var(--cyan)",
  DEFINED_IN: "var(--text-dim)",
  CONTAINS: "var(--yellow)",
};

interface Props {
  uid: string;
}

export function SymbolDetail({ uid }: Props) {
  const [data, setData] = useState<any>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    setLoading(true);
    fetch(`/api/symbol/${encodeURIComponent(uid)}`)
      .then((r) => r.json())
      .then((d) => {
        setData(d);
        setLoading(false);
      })
      .catch(() => setLoading(false));
  }, [uid]);

  if (loading) {
    return (
      <div className="space-y-3">
        {[1, 2, 3].map((i) => (
          <div key={i} className="h-8 rounded-lg pulse-glow" style={{ background: "var(--surface-2)" }} />
        ))}
      </div>
    );
  }
  if (!data?.symbol) {
    return (
      <div className="text-center py-8">
        <div className="text-2xl mb-2">?</div>
        <p className="text-xs" style={{ color: "var(--text-dim)" }}>Symbol not found</p>
      </div>
    );
  }

  const sym = data.symbol;
  const style = TYPE_STYLES[sym.node_type] || TYPE_STYLES.Function;

  return (
    <div className="space-y-5 text-xs fade-in">
      {/* Symbol header */}
      <div>
        <div className="flex items-center gap-2 mb-2">
          <span
            className="px-2 py-0.5 rounded-md text-[10px] font-semibold mono"
            style={{ color: style.color, background: style.bg }}
          >
            {sym.node_type}
          </span>
          <span className="font-bold text-sm" style={{ color: "var(--text)" }}>{sym.name}</span>
        </div>
        {sym.signature && (
          <code
            className="block p-3 rounded-lg text-[11px] mono overflow-x-auto"
            style={{ background: "var(--bg)", color: "var(--accent)", border: "1px solid var(--border)" }}
          >
            {sym.signature}
          </code>
        )}
        <div className="flex items-center gap-2 mt-2">
          <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" style={{ color: "var(--text-muted)" }}>
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
          </svg>
          <span className="mono" style={{ color: "var(--text-dim)" }}>
            {sym.file_path}:{sym.line_start}
          </span>
        </div>
        {sym.docstring && (
          <p
            className="mt-3 p-3 rounded-lg text-[11px] leading-relaxed"
            style={{ background: "var(--surface-2)", color: "var(--text-dim)", borderLeft: "2px solid var(--accent)" }}
          >
            {sym.docstring}
          </p>
        )}
      </div>

      {/* Outgoing */}
      {data.outgoing && Object.keys(data.outgoing).length > 0 && (
        <Section title="Outgoing" icon="→">
          {Object.entries(data.outgoing).map(([rel, targets]: [string, any]) => (
            <RelGroup key={rel} rel={rel} items={targets} />
          ))}
        </Section>
      )}

      {/* Incoming */}
      {data.incoming && Object.keys(data.incoming).length > 0 && (
        <Section title="Incoming" icon="←">
          {Object.entries(data.incoming).map(([rel, sources]: [string, any]) => (
            <RelGroup key={rel} rel={rel} items={sources} />
          ))}
        </Section>
      )}
    </div>
  );
}

function Section({ title, icon, children }: { title: string; icon: string; children: React.ReactNode }) {
  return (
    <div>
      <div className="flex items-center gap-2 mb-3">
        <span className="text-sm">{icon}</span>
        <h4 className="text-[10px] font-semibold uppercase tracking-wider" style={{ color: "var(--text-dim)" }}>
          {title}
        </h4>
        <div className="flex-1 h-px" style={{ background: "var(--border)" }} />
      </div>
      <div className="space-y-2">{children}</div>
    </div>
  );
}

function RelGroup({ rel, items }: { rel: string; items: any[] }) {
  const color = REL_COLORS[rel] || "var(--text-dim)";
  return (
    <div
      className="rounded-lg p-3"
      style={{ background: "var(--bg)", border: "1px solid var(--border)" }}
    >
      <div className="flex items-center gap-2 mb-2">
        <span
          className="px-1.5 py-0.5 rounded text-[10px] font-medium mono"
          style={{ color, background: `${color}15` }}
        >
          {rel}
        </span>
        <span className="text-[10px]" style={{ color: "var(--text-muted)" }}>
          {items.length}
        </span>
      </div>
      <ul className="space-y-1">
        {items.slice(0, 10).map((item, i) => (
          <li key={i} className="flex items-center gap-2 text-[11px]">
            <span className="w-1 h-1 rounded-full shrink-0" style={{ background: color }} />
            <span className="mono font-medium" style={{ color: "var(--text)" }}>{item.name}</span>
            <span className="mono truncate" style={{ color: "var(--text-muted)" }}>{item.file_path || item.file}</span>
          </li>
        ))}
        {items.length > 10 && (
          <li className="text-[10px] ml-3" style={{ color: "var(--text-muted)" }}>
            +{items.length - 10} more
          </li>
        )}
      </ul>
    </div>
  );
}
