import { useState } from 'react';
import type { Site } from '../types/site';
import { getFaviconUrl } from '../utils/favicon';

interface AdminSiteCardProps {
  site: Site;
  onEdit: (id: string) => void;
  onDelete: (id: string) => void;
}

/** 后台预览：与首页卡片相同的图标与排版，附带编辑 / 删除 / 打开 */
export function AdminSiteCard({ site, onEdit, onDelete }: AdminSiteCardProps) {
  const [imgFailed, setImgFailed] = useState(false);
  const firstLetter = site.name.charAt(0).toUpperCase();
  const faviconUrl = site.url ? getFaviconUrl(site.url) : '';
  const tagsText = site.tags?.length ? site.tags.join('、') : '';
  const clickCount = typeof site.clicks === 'number' ? site.clicks : 0;

  return (
    <div className="site-card admin-site-card">
      <span className="site-card-clicks" title="访问次数">
        {clickCount}
      </span>
      <div className="site-icon">
        {faviconUrl && !imgFailed ? (
          <img src={faviconUrl} alt="" onError={() => setImgFailed(true)} />
        ) : (
          <div className="favicon-placeholder">{firstLetter}</div>
        )}
      </div>
      <div className="site-card-body">
        <div className="site-name" title={site.name}>
          {site.name}
        </div>
        <div className="site-description" title={site.description || site.url}>
          {site.description || site.url}
        </div>
      </div>
      <div className="site-tags" title={tagsText}>
        {site.tags?.map((tag) => (
          <span key={tag} className="tag">
            {tag}
          </span>
        ))}
      </div>
      <div className="admin-site-card-toolbar">
        <button type="button" className="admin-card-btn edit" onClick={() => onEdit(site.id)}>
          编辑
        </button>
        <button type="button" className="admin-card-btn delete" onClick={() => onDelete(site.id)}>
          删除
        </button>
        <a href={site.url} target="_blank" rel="noreferrer" className="admin-card-open">
          打开
        </a>
      </div>
    </div>
  );
}
