import { useEffect, useState } from 'react';
import { useAppStore } from '../../store/appStore';
import { useScripts } from '../../hooks/useScripts';
import type { ClassDetail as ClassDetailType, MethodSummary } from '../../types/scripts';
import { WELL_KNOWN_HOOKS } from '../../types/scripts';
import styles from './ClassDetail.module.css';

export default function ClassDetail() {
  const { selectedClass, setSelectedMethod, setCenterMode } = useAppStore();
  const { getClassDetail } = useScripts();
  const [detail, setDetail] = useState<ClassDetailType | null>(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (!selectedClass) return;
    setLoading(true);
    setDetail(null);
    getClassDetail(selectedClass.name).then((d) => {
      setDetail(d);
      setLoading(false);
    });
  }, [selectedClass?.name]);

  if (!selectedClass) return null;

  const cls = detail?.class ?? selectedClass;
  const methods = detail?.methods ?? [];

  // Split well-known hooks from other methods
  const hookNames = new Set(WELL_KNOWN_HOOKS.map((h) => h.method));
  const hooks = methods.filter((m) => hookNames.has(m.name));
  const others = methods.filter((m) => !hookNames.has(m.name));

  function selectMethod(method: MethodSummary) {
    setSelectedMethod(method);
    setCenterMode('flow_method');
  }

  return (
    <div className={styles.detail}>
      {/* Header */}
      <div className={styles.header}>
        <div className={styles.titleRow}>
          <span className={`${styles.className} font-cinzel`}>{cls.name}</span>
          {cls.isGump && <span className={styles.tag}>Gump</span>}
          {cls.isMobile && <span className={`${styles.tag} ${styles.tagMobile}`}>Mobile</span>}
          {cls.isItem && <span className={`${styles.tag} ${styles.tagItem}`}>Item</span>}
        </div>
        <div className={styles.filePath}>{cls.filePath}</div>
      </div>

      {/* Inheritance */}
      <section className={styles.section}>
        <div className={`${styles.sectionTitle} font-cinzel`}>Inheritance</div>
        <div className={styles.chain}>
          {cls.baseClass ? (
            <span className={styles.chainItem}>{cls.name}</span>
          ) : null}
          {cls.baseClass && <span className={styles.arrow}>→</span>}
          <span className={styles.chainItem}>{cls.baseClass ?? cls.name}</span>
        </div>
        {cls.interfaces.length > 0 && (
          <div className={styles.interfaces}>
            implements: {cls.interfaces.join(', ')}
          </div>
        )}
      </section>

      {loading && <div className={styles.loading}>Loading methods…</div>}

      {/* Well-known hooks */}
      {hooks.length > 0 && (
        <section className={styles.section}>
          <div className={`${styles.sectionTitle} font-cinzel`}>Hooks</div>
          {hooks.map((m) => (
            <MethodRow key={m.id} method={m} onSelect={selectMethod} isHook />
          ))}
        </section>
      )}

      {/* Other methods */}
      {others.length > 0 && (
        <section className={styles.section}>
          <div className={`${styles.sectionTitle} font-cinzel`}>
            Methods ({others.length})
          </div>
          {others.map((m) => (
            <MethodRow key={m.id} method={m} onSelect={selectMethod} />
          ))}
        </section>
      )}
    </div>
  );
}

function MethodRow({
  method,
  onSelect,
  isHook,
}: {
  method: MethodSummary;
  onSelect: (m: MethodSummary) => void;
  isHook?: boolean;
}) {
  const paramStr = method.parameters
    .map((p) => `${p.type} ${p.name}`)
    .join(', ');

  return (
    <button className={`${styles.methodRow} ${isHook ? styles.hookRow : ''}`} onClick={() => onSelect(method)}>
      <div className={styles.methodSig}>
        <span className={styles.returnType}>{method.returnType}</span>
        <span className={styles.methodName}>{method.name}</span>
        <span className={styles.params}>({paramStr})</span>
        {method.isOverride && <span className={styles.modBadge}>override</span>}
        {method.callsGump && (
          <span className={`${styles.modBadge} ${styles.gumpBadge}`}>
            → {method.gumpClass ?? 'Gump'}
          </span>
        )}
      </div>
    </button>
  );
}
