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

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

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`;
}

export default function ArtifactList({ taskId, isCompleted }: { taskId: string; isCompleted: boolean }) {
  const [data, setData] = useState<ArtifactsResult | null>(null);
  const [open, setOpen] = useState(false);

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

  if (!data) return null;

  const hasDeliverable = !!data.deliverable;
  const nodeCount = data.nodes.length;

  if (!hasDeliverable && nodeCount === 0) return null;

  return (
    <div style={{ borderTop: '1px solid var(--line)', paddingTop: 8, marginTop: 8 }}>
      {/* 最终交付物 */}
      {hasDeliverable && (
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
          <span style={{ fontSize: 12, fontWeight: 700, color: 'var(--acc)' }}>📦 最终交付</span>
          <div style={{ display: 'flex', gap: 4 }}>
            <a className="btn-small" href={api.artifactDownloadUrl(taskId, data.deliverable!.path)} download
              style={{ borderColor: 'var(--acc)', color: 'var(--acc)', textDecoration: 'none', fontSize: 10 }}>
              📄 {formatSize(data.deliverable!.size)} ⬇
            </a>
          </div>
        </div>
      )}

      {/* 节点产出折叠 */}
      {nodeCount > 0 && (
        <div>
          <div onClick={() => setOpen(!open)} style={{ display: 'flex', alignItems: 'center', gap: 6, cursor: 'pointer', userSelect: 'none' }}>
            <span style={{ fontSize: 11 }}>{open ? '▼' : '▶'}</span>
            <span style={{ fontSize: 11, color: 'var(--muted)' }}>📁 {nodeCount}个节点产出</span>
          </div>
          {open && (
            <div style={{ marginTop: 4 }}>
              {data.nodes.map((node) => (
                <div key={node.node_id} style={{ padding: '4px 0 4px 12px', fontSize: 11, color: 'var(--muted)' }}>
                  <span>{node.status === 'done' ? '✅' : '🔄'}</span>{' '}
                  <span style={{ color: 'var(--fg)' }}>{node.name}</span>
                  {node.artifacts.map((a) => (
                    <span key={a.path} style={{ marginLeft: 8 }}>
                      {TYPE_ICONS[a.type]} {a.name} ({formatSize(a.size)})
                    </span>
                  ))}
                </div>
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  );
}
