import type {
  Spell,
  MagicItem,
  Weapon5e,
  Armor5e,
  Feat5e,
  Condition5e,
  CompendiumEntry,
} from '@/lib/compendium/types';

function Header({ title, subtitle }: { title: string; subtitle?: string | undefined }) {
  return (
    <header>
      <h2 className="font-display text-2xl font-bold text-accent">{title}</h2>
      {subtitle && <p className="text-sm italic text-muted">{subtitle}</p>}
    </header>
  );
}

function Traits({ traits }: { traits?: string[] | undefined }) {
  if (!traits || traits.length === 0) return null;
  return (
    <div className="flex flex-wrap gap-1">
      {traits.map((t) => (
        <span key={t} className="rounded bg-elevated px-2 py-0.5 text-xs uppercase tracking-wide text-muted">
          {t}
        </span>
      ))}
    </div>
  );
}

export function Spell5eDetail({ entry: s }: { entry: Spell }) {
  return (
    <div className="space-y-3">
      <Header title={s.name} subtitle={s.level_int === 0 ? `${s.school} cantrip` : `Level ${s.level_int} ${s.school ?? ''}`} />
      <div className="grid grid-cols-2 gap-x-6 gap-y-1 text-sm text-muted">
        <span><strong className="text-ink">Casting Time</strong> {s.casting_time}</span>
        <span><strong className="text-ink">Range</strong> {s.range}</span>
        <span><strong className="text-ink">Duration</strong> {s.duration}</span>
        <span><strong className="text-ink">Components</strong> {s.components}</span>
      </div>
      <p className="whitespace-pre-wrap text-sm text-ink">{s.desc}</p>
      {s.higher_level && (
        <p className="whitespace-pre-wrap text-sm text-muted">
          <strong className="text-ink">At Higher Levels.</strong> {s.higher_level}
        </p>
      )}
    </div>
  );
}

export function Item5eDetail({ entry: item }: { entry: MagicItem }) {
  return (
    <div className="space-y-3">
      <Header
        title={item.name}
        subtitle={
          [item.type, item.rarity].filter(Boolean).join(', ') +
          (item.requires_attunement ? ` (requires attunement ${item.requires_attunement})` : '')
        }
      />
      <p className="whitespace-pre-wrap text-sm text-ink">{item.desc}</p>
    </div>
  );
}

export function Weapon5eDetail({ entry: w }: { entry: Weapon5e }) {
  return (
    <div className="space-y-3">
      <Header title={w.name} subtitle={w.category} />
      <div className="grid grid-cols-2 gap-x-6 gap-y-1 text-sm text-muted">
        <span><strong className="text-ink">Damage</strong> {w.damage_dice} {w.damage_type}</span>
        <span><strong className="text-ink">Cost</strong> {w.cost ?? '—'}</span>
        <span><strong className="text-ink">Weight</strong> {w.weight ?? '—'}</span>
      </div>
      {w.properties && w.properties.length > 0 && (
        <p className="text-sm text-muted"><strong className="text-ink">Properties</strong> {w.properties.join(', ')}</p>
      )}
    </div>
  );
}

export function Armor5eDetail({ entry: a }: { entry: Armor5e }) {
  return (
    <div className="space-y-3">
      <Header title={a.name} subtitle={`${a.type ?? ''} armor`} />
      <div className="grid grid-cols-2 gap-x-6 gap-y-1 text-sm text-muted">
        <span><strong className="text-ink">AC</strong> {a.ac}</span>
        <span><strong className="text-ink">Cost</strong> {a.cost ?? '—'}</span>
        <span><strong className="text-ink">Weight</strong> {a.weight ?? '—'} lb</span>
        <span><strong className="text-ink">Stealth</strong> {a.stealthPenalty ? 'Disadvantage' : '—'}</span>
      </div>
    </div>
  );
}

export function Feat5eDetail({ entry: f }: { entry: Feat5e }) {
  return (
    <div className="space-y-3">
      <Header title={f.name} subtitle="Feat" />
      <p className="whitespace-pre-wrap text-sm text-ink">{f.description}</p>
    </div>
  );
}

export function Condition5eDetail({ entry: c }: { entry: Condition5e }) {
  return (
    <div className="space-y-3">
      <Header title={c.name} subtitle="Condition" />
      {c.description && <p className="text-sm text-ink">{c.description}</p>}
      {c.effects && c.effects.length > 0 && (
        <ul className="list-disc space-y-1 pl-5 text-sm text-muted">
          {c.effects.map((e, i) => <li key={i}>{e}</li>)}
        </ul>
      )}
    </div>
  );
}

/** Renderer for homebrew entries: header, field facts, description. */
export function HomebrewDetail({ entry }: { entry: CompendiumEntry }) {
  const skip = new Set(['name', 'slug', 'description', '__homebrew', '__kind']);
  const facts = Object.entries(entry).filter(([k, v]) => !skip.has(k) && v !== undefined && v !== '');
  const kind = typeof entry.__kind === 'string' ? entry.__kind : 'homebrew';
  return (
    <div className="space-y-3">
      <Header title={entry.name} subtitle={`Homebrew ${kind}`} />
      {facts.length > 0 && (
        <div className="grid grid-cols-2 gap-x-6 gap-y-1 text-sm text-muted sm:grid-cols-3">
          {facts.map(([k, v]) => (
            <span key={k}><strong className="text-ink">{k}</strong> {String(v)}</span>
          ))}
        </div>
      )}
      {entry.description ? <p className="whitespace-pre-wrap text-sm text-ink">{String(entry.description)}</p> : null}
    </div>
  );
}

/** Generic renderer for PF2e (AoN) entries: header, traits, key facts, text body. */
export function Pf2eDetail({ entry }: { entry: CompendiumEntry }) {
  const traits = (entry.trait as string[] | undefined) ?? undefined;
  const facts: [string, unknown][] = [
    ['Level', entry.level],
    ['Rarity', entry.rarity],
    ['Tradition', entry.tradition],
    ['Actions', entry.actions],
    ['Price', entry.price],
    ['AC', entry.ac],
    ['HP', entry.hp],
    ['Damage', entry.damage],
    ['Source', entry.source],
  ];
  const shown = facts.filter(
    ([k, v]) => v !== undefined && v !== null && v !== '' && !(k === 'Rarity' && v === 'common'),
  );
  const text = (entry.text as string | undefined) ?? (entry.summary as string | undefined) ?? '';

  return (
    <div className="space-y-3">
      <Header title={entry.name} subtitle={(entry.type as string | undefined) ?? undefined} />
      <Traits traits={traits} />
      {shown.length > 0 && (
        <div className="grid grid-cols-2 gap-x-6 gap-y-1 text-sm text-muted sm:grid-cols-3">
          {shown.map(([k, v]) => (
            <span key={k}><strong className="text-ink">{k}</strong> {String(v)}</span>
          ))}
        </div>
      )}
      <p className="whitespace-pre-line text-sm text-ink">{text}</p>
    </div>
  );
}
