import { useState, useEffect } from 'react';
import { api } from '../api';
import type { ArtifactsResult, ArtifactEntry, ArtifactPreviewResult } from '../api';
import { useStore } from '../store';

const TYPE_ICONS: Record<string, string> = {
  document: '📄',
  code: '💻',
  data: '📊',
  config: '⚙️',
  other: '📁',
};

const AGENT_EMOJI: Record<string, string> = {
  'pangtong-fujunshi': '🐦',
  'simayi-challenger': '🦅',
  'jiangwei-infra': '🔧',
  'guanyu-dev': '⚔️',
  'zhangfei-dev': '💪',
  'zhaoyun-data': '📊',
};

function formatSize(bytes: number): string {
  if (bytes < 1024) return `${bytes}B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
}

// ── 预览模态框 ──

function ArtifactPreviewModal({
  taskId,
  artifact,
  onClose,
}: {
  taskId: string;
  artifact: ArtifactEntry;
  onClose: () => void;
}) {
  const [preview, setPreview] = useState<ArtifactPreviewResult | null>(null);
  const [loading, setLoading] = useState(true);
  const toast = useStore((s) => s.toast);

  useEffect(() => {
    if (!artifact.previewable) {
      setLoading(false);
      return;
    }
    api.artifactPreview(taskId, artifact.path)
      .then(setPreview)
      .catch(() => toast('预览加载失败', 'err'))
      .finally(() => setLoading(false));
  }, [taskId, artifact.path]);

  return (
    <div className="modal-bg open" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()} style={{ position: 'relative', maxWidth: 700 }}>
        <button className="modal-close" onClick={onClose}>✕</button>
        <div style={{ padding: '12px 20px', borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'center', gap: 8 }}>
          <span>{TYPE_ICONS[artifact.type] || '📁'}</span>
          <span style={{ fontSize: 14, fontWeight: 700 }}>{artifact.name}</span>
          <span style={{ fontSize: 11, color: 'var(--muted)' }}>{formatSize(artifact.size)}</span>
          <a
            href={api.artifactDownloadUrl(taskId, artifact.path)}
            download
            style={{ marginLeft: 'auto', fontSize: 11, padding: '4px 10px', borderRadius: 6, border: '1px solid var(--acc)', color: 'var(--acc)', textDecoration: 'none' }}
          >⬇ 下载</a>
        </div>
        <div style={{ padding: 20, maxHeight: '60vh', overflowY: 'auto' }}>
          {loading && <div style={{ color: 'var(--muted)', textAlign: 'center' }}>加载中...</div>}
          {!loading && preview && !preview.previewable && (
            <div style={{ textAlign: 'center', color: 'var(--muted)', padding: 40 }}>
              <div style={{ fontSize: 24, marginBottom: 8 }}>📁</div>
              <div>{preview.message || '文件过大或不可预览，请下载查看'}</div>
            </div>
          )}
          {!loading && preview?.content && (
            preview.render_as === 'markdown' ? (
              <div className="md-preview" dangerouslySetInnerHTML={{ __html: simpleMarkdown(preview.content) }} />
            ) : preview.render_as === 'table' ? (
              <pre style={{ fontSize: 12, overflow: 'auto' }}>{preview.content}</pre>
            ) : (
              <pre style={{ background: '#0d1117', padding: 12, borderRadius: 8, fontSize: 12, overflow: 'auto', color: '#e6edf3', fontFamily: 'monospace' }}>{preview.content}</pre>
            )
          )}
        </div>
      </div>
    </div>
  );
}

// ── 简易 Markdown 渲染 ──

function simpleMarkdown(text: string): string {
  return text
    .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
    .replace(/^### (.+)$/gm, '<h3 style="font-size:14px;font-weight:700;margin:8px 0 4px">$1</h3>')
    .replace(/^## (.+)$/gm, '<h2 style="font-size:15px;font-weight:700;margin:10px 0 6px">$1</h2>')
    .replace(/^# (.+)$/gm, '<h1 style="font-size:17px;font-weight:700;margin:12px 0 8px">$1</h1>')
    .replace(/\*\*(.+?)\*\*/g, '<b>$1</b>')
    .replace(/`([^`]+)`/g, '<code style="background:var(--panel2);padding:1px 4px;border-radius:3px;font-size:11px">$1</code>')
    .replace(/\n/g, '<br/>');
}

// ── 主面板 ──

export default function ArtifactPanel({ taskId, isCompleted }: { taskId: string; isCompleted: boolean }) {
  const [data, setData] = useState<ArtifactsResult | null>(null);
  const [previewTarget, setPreviewTarget] = useState<ArtifactEntry | null>(null);
  const toast = useStore((s) => s.toast);

  useEffect(() => {
    api.artifacts(taskId)
      .then(setData)
      .catch(() => {});
  }, [taskId]);

  if (!data) return <div style={{ color: 'var(--muted)', textAlign: 'center', padding: 20 }}>加载中...</div>;

  return (
    <div>
      {/* 最终交付物 */}
      <div style={{ marginBottom: 16, padding: 16, borderRadius: 10, border: '1px solid var(--acc)', background: 'rgba(201,162,39,0.04)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
          <span style={{ fontSize: 16 }}>📋</span>
          <span style={{ fontSize: 14, fontWeight: 700, color: 'var(--acc)' }}>最终交付物</span>
        </div>
        {data.deliverable ? (
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: 10, background: 'var(--panel2)', borderRadius: 8 }}>
            <span style={{ fontSize: 20 }}>{TYPE_ICONS[data.deliverable.type]}</span>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 600 }}>{data.deliverable.name}</div>
              <div style={{ fontSize: 11, color: 'var(--muted)' }}>{formatSize(data.deliverable.size)}</div>
            </div>
            <div style={{ display: 'flex', gap: 4 }}>
              <button className="btn-small" style={{ borderColor: 'var(--acc)', color: 'var(--acc)' }} onClick={() => setPreviewTarget(data.deliverable!)}>预览</button>
              <a className="btn-small" href={api.artifactDownloadUrl(taskId, data.deliverable.path)} download style={{ borderColor: 'var(--acc)', color: 'var(--acc)', textDecoration: 'none' }}>下载</a>
            </div>
          </div>
        ) : (
          <div style={{ fontSize: 12, color: 'var(--muted)', padding: 8 }}>
            {isCompleted ? '无交付物' : '最终交付物将在任务完成后生成'}
          </div>
        )}
      </div>

      {/* 节点产出 */}
      <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--muted)', marginBottom: 10 }}>📁 节点产出</div>
      {data.nodes.length === 0 ? (
        <div style={{ fontSize: 12, color: 'var(--muted)', textAlign: 'center', padding: 20 }}>暂无节点产出</div>
      ) : data.nodes.map((node) => (
        <div key={node.node_id} style={{ marginBottom: 8, padding: 12, borderRadius: 10, background: 'var(--panel)', border: '1px solid var(--line)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
            <span>{node.status === 'done' ? '✅' : node.status === 'waiting_human' ? '🛐' : '🔄'}</span>
            <span style={{ fontSize: 13, fontWeight: 600 }}>{node.name}</span>
            <span style={{ fontSize: 11, color: 'var(--muted)' }}>{AGENT_EMOJI[node.agent_id] || ''} {node.agent_id}</span>
            <span className={`tag tag-${node.status === 'done' ? 'done' : node.status === 'waiting_human' ? 'waiting' : 'exec'}`} style={{ marginLeft: 'auto' }}>
              {node.status}
            </span>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
            {node.artifacts.map((a) => (
              <div key={a.path} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '6px 8px', background: 'var(--panel2)', borderRadius: 6 }}>
                <span>{TYPE_ICONS[a.type] || '📁'}</span>
                <span style={{ fontSize: 12 }}>{a.name}</span>
                <span style={{ fontSize: 10, color: 'var(--muted)' }}>{formatSize(a.size)}</span>
                <div style={{ marginLeft: 'auto', display: 'flex', gap: 3 }}>
                  {a.previewable && (
                    <button className="btn-small" style={{ fontSize: 10, padding: '2px 6px' }} onClick={() => setPreviewTarget(a)}>预览</button>
                  )}
                  <a className="btn-small" href={api.artifactDownloadUrl(taskId, a.path)} download style={{ fontSize: 10, padding: '2px 6px', textDecoration: 'none' }}>下载</a>
                </div>
              </div>
            ))}
          </div>
        </div>
      ))}

      {/* 预览模态框 */}
      {previewTarget && (
        <ArtifactPreviewModal taskId={taskId} artifact={previewTarget} onClose={() => setPreviewTarget(null)} />
      )}
    </div>
  );
}
