'use client';
import { useTranslations } from 'next-intl';
import { useRouter } from 'next/navigation';
import { useState } from 'react';

type Post = {
  id: number;
  slug: string;
  title: string;
  titleEn: string | null;
  coverImage: string;
  status: string | null;
  publishDate: string | null;
  likeCount: number | null;
  dislikeCount: number | null;
};

export function PostList({ posts }: { posts: Post[] }) {
  const t = useTranslations('editor');
  const router = useRouter();
  const [deletingId, setDeletingId] = useState<number | null>(null);
  const [confirmId, setConfirmId] = useState<number | null>(null);
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

  const handleDelete = async (id: number) => {
    setDeletingId(id);
    setMessage(null);
    try {
      const res = await fetch(`/api/blog/${id}?id=${id}`, { method: 'DELETE' });
      const data = await res.json().catch(() => ({}));
      if (res.ok) {
        setMessage({ type: 'success', text: '删除成功' });
        router.refresh();
      } else {
        setMessage({ type: 'error', text: data.error || '删除失败' });
      }
    } catch {
      setMessage({ type: 'error', text: '网络错误，删除失败' });
    } finally {
      setDeletingId(null);
      setConfirmId(null);
    }
  };

  return (
    <>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1rem' }}>
        <h3>{t('title')}</h3>
        <a href="/admin/editor/new" className="header-btn primary">+ {t('preview')}</a>
      </div>

      {message && (
        <div
          className={message.type === 'success' ? 'modal-success' : 'modal-error'}
          style={{ marginBottom: '1rem' }}
        >
          {message.text}
        </div>
      )}

      {confirmId !== null && (
        <div className="modal-overlay" style={{
          position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.4)',
          display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000,
        }}>
          <div className="modal-content" style={{
            background: 'var(--card)', padding: '1.5rem', borderRadius: '12px',
            maxWidth: '360px', width: '90%', textAlign: 'center',
          }}>
            <p style={{ marginBottom: '1.2rem' }}>确认删除这篇博文？此操作不可撤销。</p>
            <div style={{ display: 'flex', gap: '0.6rem', justifyContent: 'center' }}>
              <button
                className="header-btn"
                onClick={() => setConfirmId(null)}
                style={{ padding: '0.5rem 1.2rem' }}
              >
                取消
              </button>
              <button
                className="header-btn primary"
                onClick={() => handleDelete(confirmId)}
                disabled={deletingId === confirmId}
                style={{
                  padding: '0.5rem 1.2rem',
                  background: 'var(--danger)',
                  borderColor: 'var(--danger)',
                }}
              >
                {deletingId === confirmId ? '删除中...' : '确认删除'}
              </button>
            </div>
          </div>
        </div>
      )}

      <table className="post-list-table">
        <thead>
          <tr>
            <th>封面</th>
            <th>标题</th>
            <th>状态</th>
            <th>发布日期</th>
            <th>♥</th>
            <th>✗</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          {posts.map(p => (
            <tr key={p.id}>
              <td>
                <img src={p.coverImage} alt="" style={{ width: '60px', height: '40px', objectFit: 'cover', borderRadius: '4px' }} />
              </td>
              <td><a href={`/blog/${p.slug}`} target="_blank">{p.title || p.titleEn}</a></td>
              <td>{p.status === 'published' ? '✓ 已发布' : '草稿'}</td>
              <td>{p.publishDate || '-'}</td>
              <td>{p.likeCount}</td>
              <td>{p.dislikeCount}</td>
              <td>
                <a href={`/admin/editor/${p.slug}`} className="header-btn" style={{ padding: '0.3rem 0.6rem', fontSize: '0.75rem' }}>编辑</a>
                {' '}
                <button
                  onClick={() => setConfirmId(p.id)}
                  className="header-btn"
                  style={{ padding: '0.3rem 0.6rem', fontSize: '0.75rem', color: 'var(--danger)', borderColor: 'var(--danger)' }}
                >
                  {t('delete')}
                </button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </>
  );
}
