import { useEffect, useState } from 'react'
import { X, ExternalLink, GripVertical } from 'lucide-react'

// 文件预览右侧滑出面板
// Props:
//   url       要预览的完整 URL（一般是 /api/skill-run/outputs/:sid/:filename）
//   filename  顶部展示的文件名（可选；不传时从 url 末尾推断）
//   visible   是否可见（控制滑入/滑出动画）
//   onClose   关闭回调
//
// 行为：
// - 桌面端从右侧滑入，宽度默认 40vw，左边缘可拖拽（min 320px / max 70vw）
// - 移动端（< 768px）全屏覆盖
// - 用 iframe 加载 url，HTML 文件直接渲染，其他文本类文件浏览器自带渲染
// - 顶部工具栏：文件名 + 新窗口打开 + 关闭
// - ESC 关闭
export default function PreviewPanel({ url, filename, visible, onClose }) {
  const [width, setWidth] = useState(() =>
    typeof window !== 'undefined' ? Math.round(window.innerWidth * 0.4) : 600
  )
  const [dragging, setDragging] = useState(false)
  const [isMobile, setIsMobile] = useState(() =>
    typeof window !== 'undefined' ? window.innerWidth < 768 : false
  )

  useEffect(() => {
    const onResize = () => {
      setIsMobile(window.innerWidth < 768)
      setWidth((w) => Math.min(w, Math.round(window.innerWidth * 0.7)))
    }
    window.addEventListener('resize', onResize)
    return () => window.removeEventListener('resize', onResize)
  }, [])

  useEffect(() => {
    if (!dragging) return
    const onMove = (e) => {
      const x = e.clientX
      const next = Math.max(320, Math.min(window.innerWidth * 0.7, window.innerWidth - x))
      setWidth(next)
    }
    const onUp = () => setDragging(false)
    document.body.style.userSelect = 'none'
    document.body.style.cursor = 'col-resize'
    window.addEventListener('mousemove', onMove)
    window.addEventListener('mouseup', onUp)
    return () => {
      document.body.style.userSelect = ''
      document.body.style.cursor = ''
      window.removeEventListener('mousemove', onMove)
      window.removeEventListener('mouseup', onUp)
    }
  }, [dragging])

  useEffect(() => {
    if (!visible) return
    const onKey = (e) => { if (e.key === 'Escape') onClose?.() }
    window.addEventListener('keydown', onKey)
    return () => window.removeEventListener('keydown', onKey)
  }, [visible, onClose])

  const panelWidth = isMobile ? '100vw' : `${width}px`
  const displayName = filename || (url ? decodeURIComponent(url.split('?')[0].split('/').pop() || '') : '')

  return (
    <>
      {/* 拖拽时全屏覆盖防止 iframe 抢占鼠标事件 */}
      {dragging && <div className="fixed inset-0 z-[70] cursor-col-resize" />}

      <div
        className="fixed top-0 right-0 h-full bg-white border-l border-gray-200 shadow-2xl z-[60] flex flex-col"
        style={{
          width: panelWidth,
          transform: visible ? 'translateX(0)' : 'translateX(100%)',
          transition: dragging ? 'none' : 'transform 0.2s ease',
          pointerEvents: visible ? 'auto' : 'none',
        }}
      >
        {/* 左边缘拖拽条（仅桌面） */}
        {!isMobile && visible && (
          <div
            onMouseDown={(e) => { e.preventDefault(); setDragging(true) }}
            className="absolute left-0 top-0 h-full w-1.5 -ml-[3px] cursor-col-resize group z-10"
            title="拖拽调整宽度"
          >
            <div className="absolute inset-y-0 left-1/2 -translate-x-1/2 w-px bg-transparent group-hover:bg-brand-400 transition-colors" />
            <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-4 h-10 grid place-items-center rounded bg-white border border-gray-200 opacity-0 group-hover:opacity-100 transition-opacity">
              <GripVertical size={12} className="text-gray-400" />
            </div>
          </div>
        )}

        {/* Header */}
        <div className="flex items-center gap-1.5 px-3 py-2 border-b border-gray-200 bg-white flex-shrink-0">
          <span className="text-[13px] font-medium text-gray-800 truncate flex-1 min-w-0" title={displayName}>
            <span className="text-gray-400 mr-1">📄</span>
            {displayName || '预览'}
          </span>
          {url && (
            <a
              href={url}
              target="_blank"
              rel="noreferrer"
              className="w-7 h-7 grid place-items-center rounded-md text-gray-500 hover:bg-gray-100 hover:text-brand-600"
              title="新窗口打开"
            >
              <ExternalLink size={14} />
            </a>
          )}
          <button
            onClick={onClose}
            className="w-7 h-7 grid place-items-center rounded-md text-gray-500 hover:bg-gray-100"
            title="关闭 (ESC)"
          >
            <X size={16} />
          </button>
        </div>

        {/* Body */}
        <div className="flex-1 overflow-hidden bg-gray-50">
          {visible && url ? (
            <iframe
              key={url}
              src={url}
              title={displayName || 'preview'}
              className="w-full h-full border-0 bg-white"
              sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-modals"
            />
          ) : (
            <div className="h-full grid place-items-center text-[13px] text-gray-400">
              {visible ? '无内容' : ''}
            </div>
          )}
        </div>
      </div>
    </>
  )
}
