import { Link } from 'react-router-dom';
import type { DocPage, Reference } from '../../lib/kanbanApi';
import type { CustomPage } from '../../lib/pagesApi';

interface ReferenceLinksProps {
  references: Reference[];
  pages: DocPage[];
  /** User-created custom pages, used to resolve icons/blurbs for `custom` refs. */
  customPages?: CustomPage[];
  /** Compact chips (card footer) vs full rows (expanded card). */
  compact?: boolean;
  onRemove?: (href: string) => void;
}

const TYPE_ICON: Record<Reference['type'], string> = {
  doc: '◈',
  custom: '✦',
  code: '📁',
  demo: '▶',
  external: '↗',
};

/** Build the internal route for a custom page reference. */
const customHref = (slug: string) => `/docs/custom/${slug}`;

export function ReferenceLinks({ references, pages, customPages, compact, onRemove }: ReferenceLinksProps) {
  if (references.length === 0) {
    return compact ? null : (
      <p style={{ fontSize: '0.75rem', color: 'var(--muted)', fontStyle: 'italic', margin: 0 }}>
        No references yet.
      </p>
    );
  }

  const pageByPath = new Map(pages.map((p) => [p.path, p]));
  const customByHref = new Map((customPages ?? []).map((p) => [customHref(p.slug), p]));

  return (
    <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px' }}>
      {references.map((r) => {
        const customPage = customByHref.get(r.href);
        const icon =
          r.type === 'doc'
            ? (pageByPath.get(r.href)?.icon ?? TYPE_ICON.doc)
            : r.type === 'custom'
              ? (customPage?.icon ?? TYPE_ICON.custom)
              : TYPE_ICON[r.type];
        const inner = (
          <>
            <span style={{ opacity: 0.8 }}>{icon}</span> {r.label}
          </>
        );

        // `doc` and `custom` references are both internal routes.
        const isInternal = r.type === 'doc' || r.type === 'custom';
        const body = isInternal ? (
          <Link
            to={r.href}
            onClick={(e) => e.stopPropagation()}
            style={chipStyle(r.type, compact)}
            title={
              r.type === 'doc'
                ? (pageByPath.get(r.href)?.blurb ?? r.label)
                : (customPage?.blurb ?? r.label)
            }
          >
            {inner}
          </Link>
        ) : (
          <a
            href={r.href}
            target={r.type === 'external' ? '_blank' : undefined}
            rel={r.type === 'external' ? 'noreferrer' : undefined}
            onClick={(e) => e.stopPropagation()}
            style={chipStyle(r.type, compact)}
          >
            {inner}
          </a>
        );

        return (
          <span key={r.href} style={{ display: 'inline-flex', alignItems: 'center' }}>
            {body}
            {r.removable && onRemove && (
              <button
                type="button"
                onClick={(e) => {
                  e.stopPropagation();
                  onRemove(r.href);
                }}
                title="Remove reference"
                style={{
                  border: 'none',
                  background: 'transparent',
                  color: 'var(--muted)',
                  cursor: 'pointer',
                  fontSize: '0.7rem',
                  padding: '0 2px',
                  lineHeight: 1,
                }}
              >
                ×
              </button>
            )}
          </span>
        );
      })}
    </div>
  );
}

function chipStyle(type: Reference['type'], compact?: boolean): React.CSSProperties {
  const color =
    type === 'doc'
      ? 'var(--cyan)'
      : type === 'custom'
        ? 'var(--purple)'
        : type === 'code'
          ? 'var(--fg-dim)'
          : type === 'demo'
            ? 'var(--accent)'
            : 'var(--muted)';
  const accentBorder =
    type === 'doc' ? 'rgba(100,180,255,0.3)' : type === 'custom' ? 'rgba(167,139,250,0.3)' : 'var(--border)';
  const accentBg =
    type === 'doc' ? 'rgba(100,180,255,0.08)' : type === 'custom' ? 'rgba(167,139,250,0.08)' : 'var(--surface-raised)';
  return {
    fontSize: compact ? '0.65rem' : '0.72rem',
    padding: '2px 7px',
    borderRadius: 'var(--radius-sm)',
    border: `1px solid ${accentBorder}`,
    background: accentBg,
    color,
    textDecoration: 'none',
    display: 'inline-flex',
    alignItems: 'center',
    gap: '4px',
    whiteSpace: 'nowrap',
  };
}
