import type { MindSpacePage } from '../types';
import { WorkCover } from './WorkCover';

const ACCESS_MODE_ICONS: Record<string, { icon: string; title: string }> = {
  public:        { icon: '🌐', title: '完全公开' },
  password:      { icon: '🔑', title: '密码访问' },
  private_link:  { icon: '🔗', title: '私密链接' },
  time_limited:  { icon: '⏱', title: '限时访问' },
  login_required:{ icon: '👤', title: '仅登录用户' },
  owner_only:    { icon: '🔒', title: '仅自己可见' },
};

const PAGE_STATUS_LABELS: Record<string, string> = {
  draft: '草稿',
  reviewing: '待检查',
  risk_found: '发现风险',
  ready: '可发布',
  published: '已公开',
  protected: '受保护',
  expired: '已过期',
  offline: '已下线',
};

const TEMPLATE_LABELS: Record<string, string> = {
  editorial: '长文',
  report: '报告',
  'knowledge-card': '知识卡片',
  profile: '个人介绍',
};

function feedTypeLabel(page: MindSpacePage) {
  if (page.contentFormat === 'html') return '网页';
  return TEMPLATE_LABELS[page.templateId] ?? page.templateId;
}

function formatFeedDate(timestamp: number) {
  const date = new Date(timestamp);
  const now = new Date();
  const diffMs = now.getTime() - date.getTime();
  const diffDays = Math.floor(diffMs / (24 * 60 * 60 * 1000));
  if (diffDays < 1) return '今天';
  if (diffDays === 1) return '昨天';
  if (diffDays < 7) return `${diffDays}天前`;
  return date.toLocaleDateString('zh-CN', { month: 'numeric', day: 'numeric' });
}

const PREVIEW_THUMBNAILS: Record<string, string> = {
  'page-1': '/thumbnail-demo/mapo-tofu-feed.svg',
  'page-2': '/thumbnail-demo/malaysia-travel-feed.svg',
};

export function MindSpaceFeedCard({
  page,
  previewMode = false,
  onClick,
  actions,
}: {
  page: MindSpacePage;
  previewMode?: boolean;
  onClick: () => void;
  actions?: { label: string; onClick: (e: React.MouseEvent) => void }[];
}) {
  const typeLabel = feedTypeLabel(page);
  const isHtml = page.contentFormat === 'html';
  const previewThumbnail = previewMode ? PREVIEW_THUMBNAILS[page.id] : null;

  return (
    <div className="mindspace-feed-card-wrap">
      <button type="button" className="mindspace-feed-card" onClick={onClick}>
        <div className="mindspace-feed-cover">
          {isHtml ? (
            <WorkCover
              coverMode="thumbnail-first"
              thumbnailUrl={
                previewThumbnail ??
                `/api/mindspace/v1/pages/${page.id}/thumbnail?v=${page.updatedAt}`
              }
              previewUrl={`/api/mindspace/v1/pages/${page.id}/preview?v=${page.versionNo ?? page.updatedAt}`}
              fallbackLabel={typeLabel}
              title={page.title}
              imageClassName="mindspace-feed-cover-media"
              previewFrameClassName="mindspace-feed-cover-preview"
            />
          ) : (
            <div className="mindspace-feed-cover-fallback" aria-hidden="true">
              <span>{typeLabel}</span>
            </div>
          )}
          <span className="mindspace-feed-badge">{typeLabel}</span>
        </div>
        <div className="mindspace-feed-body">
          <h3 className="mindspace-feed-title">{page.title}</h3>
          <p className="mindspace-feed-meta">
            {page.publicationAccessMode && ACCESS_MODE_ICONS[page.publicationAccessMode] ? (
              <span
                className="mindspace-feed-access-icon"
                title={ACCESS_MODE_ICONS[page.publicationAccessMode].title}
                aria-label={ACCESS_MODE_ICONS[page.publicationAccessMode].title}
              >
                {ACCESS_MODE_ICONS[page.publicationAccessMode].icon}
              </span>
            ) : null}
            {PAGE_STATUS_LABELS[page.status] ?? page.status} · {formatFeedDate(page.updatedAt)}
          </p>
        </div>
      </button>
      {actions && actions.length > 0 && (
        <div className="mindspace-feed-card-actions">
          {actions.map((action) => (
            <button
              key={action.label}
              type="button"
              onClick={(event) => {
                event.stopPropagation();
                action.onClick(event);
              }}
            >
              {action.label}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}
