import { useState } from 'react';
import { createPortal } from 'react-dom';

interface RefItem {
  type?: string;
  url?: string;
  name?: string;
  label?: string;
  thumb_url?: string;
  role?: string;
}

interface Props {
  references: RefItem[];
}

export function ReferenceList({ references }: Props) {
  const [lightboxUrl, setLightboxUrl] = useState<string | null>(null);
  const [playingMedia, setPlayingMedia] = useState<{ url: string; type: 'video' | 'audio' } | null>(null);

  if (references.length === 0) return null;

  const handleDownload = (url: string, label: string) => {
    const a = document.createElement('a');
    a.href = url;
    a.download = label;
    a.target = '_blank';
    a.rel = 'noopener noreferrer';
    a.click();
  };

  return (
    <>
      <div style={refsGrid}>
        {references.map((ref, i) => {
          const thumbUrl = ref.thumb_url || ref.url || '';
          const fullUrl = ref.url || '';
          const isAudio = ref.type === 'audio';
          const isVideo = ref.type === 'video';
          const label = ref.label || ref.name || ref.type || `素材${i + 1}`;
          const hasUrl = fullUrl && !fullUrl.startsWith('asset://');

          return (
            <div key={i} style={refItem} title={label}>
              {/* Thumbnail area */}
              <div style={thumbWrap}>
                {isAudio ? (
                  <div
                    style={{ ...placeholder, cursor: hasUrl ? 'pointer' : 'default' }}
                    onClick={() => hasUrl && setPlayingMedia({ url: fullUrl, type: 'audio' })}
                  >♫</div>
                ) : isVideo ? (
                  <div
                    style={{ ...placeholder, cursor: hasUrl ? 'pointer' : 'default' }}
                    onClick={() => hasUrl && setPlayingMedia({ url: fullUrl, type: 'video' })}
                  >▶</div>
                ) : thumbUrl && !thumbUrl.startsWith('asset://') ? (
                  <img
                    src={thumbUrl}
                    alt=""
                    style={refImgStyle}
                    onClick={() => thumbUrl && !thumbUrl.startsWith('asset://') && setLightboxUrl(thumbUrl)}
                  />
                ) : (
                  <div style={placeholder}>?</div>
                )}
                {/* Download button */}
                {hasUrl && (
                  <button
                    style={downloadBtn}
                    onClick={(e) => { e.stopPropagation(); handleDownload(fullUrl, label); }}
                    title="下载"
                  >↓</button>
                )}
              </div>
              <div style={refLabel}>{label}</div>
            </div>
          );
        })}
      </div>

      {/* Image lightbox — Portal 到 body 跳出父级 backdrop-filter stacking context,
          否则视觉全屏但命中区域被限制在 modal inner 内,点 modal 外暗色会误触 modal close。
          stopPropagation 仍保留作为 React 事件链兜底。 */}
      {lightboxUrl && createPortal(
        <div style={overlay} onClick={(e) => { e.stopPropagation(); setLightboxUrl(null); }}>
          <img src={lightboxUrl} alt="" style={{ maxWidth: '90vw', maxHeight: '90vh', borderRadius: 8 }} />
        </div>,
        document.body
      )}

      {/* Video/Audio player modal — 同 Portal 处理 */}
      {playingMedia && createPortal(
        <div style={overlay} onClick={(e) => { e.stopPropagation(); setPlayingMedia(null); }}>
          <div style={playerWrap} onClick={(e) => e.stopPropagation()}>
            <button style={playerClose} onClick={() => setPlayingMedia(null)}>✕</button>
            {playingMedia.type === 'video' ? (
              <video
                src={playingMedia.url}
                controls
                autoPlay
                style={{ maxWidth: '80vw', maxHeight: '70vh', borderRadius: 8 }}
              />
            ) : (
              <div style={audioWrap}>
                <div style={{ fontSize: 48, marginBottom: 16 }}>♫</div>
                <audio src={playingMedia.url} controls autoPlay style={{ width: 320 }} />
              </div>
            )}
          </div>
        </div>,
        document.body
      )}
    </>
  );
}

// Styles
const overlay: React.CSSProperties = {
  position: 'fixed', inset: 0, background: 'var(--color-overlay-strong)', display: 'flex',
  alignItems: 'center', justifyContent: 'center', zIndex: 10002,
};
const refsGrid: React.CSSProperties = {
  display: 'flex', gap: 8, flexWrap: 'wrap',
};
const refItem: React.CSSProperties = {
  width: 80, textAlign: 'center',
};
const thumbWrap: React.CSSProperties = {
  position: 'relative', width: 80, height: 80,
};
const refImgStyle: React.CSSProperties = {
  width: 80, height: 80, objectFit: 'cover', borderRadius: 6, cursor: 'pointer',
  border: '1px solid var(--color-border-modal)',
};
const placeholder: React.CSSProperties = {
  width: 80, height: 80, borderRadius: 6, background: 'var(--color-bg-placeholder)',
  border: '1px solid var(--color-border-modal)', display: 'flex', alignItems: 'center',
  justifyContent: 'center', fontSize: 24, color: 'var(--color-text-tertiary)',
};
const downloadBtn: React.CSSProperties = {
  position: 'absolute', bottom: 4, right: 4,
  width: 22, height: 22, borderRadius: 4,
  background: 'var(--color-shadow-modal)', border: 'none',
  color: '#fff', fontSize: 12, cursor: 'pointer',
  display: 'flex', alignItems: 'center', justifyContent: 'center',
};
const refLabel: React.CSSProperties = {
  fontSize: 10, color: 'var(--color-text-tertiary)', marginTop: 4, overflow: 'hidden',
  textOverflow: 'ellipsis', whiteSpace: 'nowrap',
};
const playerWrap: React.CSSProperties = {
  position: 'relative', background: 'var(--color-bg-modal)', borderRadius: 12,
  padding: 24, border: '1px solid var(--color-border-modal)',
};
const playerClose: React.CSSProperties = {
  position: 'absolute', top: 8, right: 12,
  background: 'none', border: 'none', color: 'var(--color-text-tertiary)',
  fontSize: 16, cursor: 'pointer',
};
const audioWrap: React.CSSProperties = {
  display: 'flex', flexDirection: 'column', alignItems: 'center',
  padding: '20px 40px', color: 'var(--color-text-tertiary)',
};
