import { useEffect, useState, useCallback } from 'react';

const token = () => localStorage.getItem('admin_token');
const authFetch = (url, opts = {}) =>
  fetch(url, { ...opts, headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token()}`, ...opts.headers } });

const EMPTY = { title: '', category: '뉴스룸', summary: '', content: '', thumbnailUrl: '', visible: true };
const CATS = ['뉴스룸', '기술블로그', '공지사항', '보도자료', '이벤트', '보안'];

export default function AdminNews() {
  const [page, setPage] = useState(0);
  const [data, setData] = useState({ content: [], totalPages: 0, totalElements: 0 });
  const [modal, setModal] = useState(null);      // null | 'create' | 'edit'
  const [form, setForm] = useState(EMPTY);
  const [editId, setEditId] = useState(null);
  const [saving, setSaving] = useState(false);
  const [toast, setToast] = useState(null);

  const showToast = (msg, type = 'success') => {
    setToast({ msg, type });
    setTimeout(() => setToast(null), 2500);
  };

  const load = useCallback(() => {
    authFetch(`/api/admin/news?page=${page}&size=10`)
      .then(r => r.json()).then(setData);
  }, [page]);

  useEffect(() => { load(); }, [load]);

  const openCreate = () => { setForm(EMPTY); setEditId(null); setModal('form'); };
  const openEdit = (n) => { setForm({ ...n }); setEditId(n.id); setModal('form'); };

  const handleSave = async () => {
    setSaving(true);
    const url = editId ? `/api/admin/news/${editId}` : '/api/admin/news';
    const method = editId ? 'PUT' : 'POST';
    const res = await authFetch(url, { method, body: JSON.stringify(form) });
    setSaving(false);
    if (res.ok) { setModal(null); load(); showToast(editId ? '수정되었습니다.' : '등록되었습니다.'); }
    else showToast('저장 실패', 'error');
  };

  const handleDelete = async (id) => {
    if (!confirm('삭제하시겠습니까?')) return;
    const res = await authFetch(`/api/admin/news/${id}`, { method: 'DELETE' });
    if (res.ok) { load(); showToast('삭제되었습니다.'); }
  };

  const toggleVisible = async (id) => {
    await authFetch(`/api/admin/news/${id}/visibility`, { method: 'PATCH' });
    load();
  };

  const set = (k, v) => setForm(p => ({ ...p, [k]: v }));

  return (
    <>
      {toast && (
        <div className="admin-toast">
          <div className={`toast-item ${toast.type}`}>{toast.msg}</div>
        </div>
      )}

      <div className="admin-card">
        <div className="admin-toolbar">
          <span style={{ fontSize: 13, color: '#64748b' }}>전체 {data.totalElements}건</span>
          <div className="admin-toolbar-right">
            <button className="btn btn-primary" onClick={openCreate}>＋ 뉴스 등록</button>
          </div>
        </div>

        <div className="admin-table-wrap">
          <table className="admin-table">
            <thead>
              <tr>
                <th>No</th><th>제목</th><th>카테고리</th><th>공개</th><th>조회수</th><th>등록일</th><th>관리</th>
              </tr>
            </thead>
            <tbody>
              {data.content.map((n, i) => (
                <tr key={n.id}>
                  <td style={{ color: '#94a3b8', fontSize: 12 }}>{data.totalElements - page * 10 - i}</td>
                  <td><span className="truncate" style={{ display: 'block' }}>{n.title}</span></td>
                  <td><span className={`badge ${n.category === '보도자료' ? 'badge-blue' : n.category === '이벤트' ? 'badge-orange' : 'badge-gray'}`}>{n.category}</span></td>
                  <td>
                    <button onClick={() => toggleVisible(n.id)}
                      className={`badge ${n.visible ? 'badge-green' : 'badge-red'}`}
                      style={{ cursor: 'pointer', border: 'none' }}>
                      {n.visible ? '공개' : '비공개'}
                    </button>
                  </td>
                  <td>{n.viewCount}</td>
                  <td style={{ fontSize: 12, color: '#94a3b8' }}>{n.createdAt?.slice(0, 10)}</td>
                  <td>
                    <div className="action-btns">
                      <button className="btn btn-outline btn-sm" onClick={() => openEdit(n)}>수정</button>
                      <button className="btn btn-danger btn-sm" onClick={() => handleDelete(n.id)}>삭제</button>
                    </div>
                  </td>
                </tr>
              ))}
              {!data.content.length && (
                <tr><td colSpan={7}><div className="empty-state"><div className="empty-icon">📰</div><p>등록된 뉴스가 없습니다.</p></div></td></tr>
              )}
            </tbody>
          </table>
        </div>

        {data.totalPages > 1 && (
          <div className="admin-pagination">
            <span className="admin-pagination-info">페이지 {page + 1} / {data.totalPages}</span>
            <div className="pagination-btns">
              <button disabled={page === 0} onClick={() => setPage(p => p - 1)}>‹</button>
              {Array.from({ length: data.totalPages }, (_, i) => (
                <button key={i} className={page === i ? 'active' : ''} onClick={() => setPage(i)}>{i + 1}</button>
              ))}
              <button disabled={page >= data.totalPages - 1} onClick={() => setPage(p => p + 1)}>›</button>
            </div>
          </div>
        )}
      </div>

      {modal === 'form' && (
        <div className="modal-backdrop" onClick={e => e.target === e.currentTarget && setModal(null)}>
          <div className="modal">
            <div className="modal-header">
              <h3>{editId ? '뉴스 수정' : '뉴스 등록'}</h3>
              <button onClick={() => setModal(null)}>✕</button>
            </div>
            <div className="modal-body">
              <div className="form-group">
                <label>제목 *</label>
                <input className="form-control" value={form.title} onChange={e => set('title', e.target.value)} placeholder="뉴스 제목을 입력하세요" />
              </div>
              <div className="form-row">
                <div className="form-group">
                  <label>카테고리</label>
                  <select className="form-control" value={form.category} onChange={e => set('category', e.target.value)}>
                    {CATS.map(c => <option key={c}>{c}</option>)}
                  </select>
                </div>
                <div className="form-group">
                  <label>공개 여부</label>
                  <select className="form-control" value={form.visible} onChange={e => set('visible', e.target.value === 'true')}>
                    <option value="true">공개</option>
                    <option value="false">비공개</option>
                  </select>
                </div>
              </div>
              <div className="form-group">
                <label>요약</label>
                <input className="form-control" value={form.summary || ''} onChange={e => set('summary', e.target.value)} placeholder="목록에 표시될 요약 문구" />
              </div>
              <div className="form-group">
                <label>썸네일 URL</label>
                <input className="form-control" value={form.thumbnailUrl || ''} onChange={e => set('thumbnailUrl', e.target.value)} placeholder="https://..." />
              </div>
              <div className="form-group">
                <label>본문 내용 *</label>
                <textarea className="form-control" rows={8} value={form.content || ''} onChange={e => set('content', e.target.value)} placeholder="뉴스 본문 내용을 입력하세요" />
              </div>
            </div>
            <div className="modal-footer">
              <button className="btn btn-outline" onClick={() => setModal(null)}>취소</button>
              <button className="btn btn-primary" onClick={handleSave} disabled={saving || !form.title}>
                {saving ? '저장 중...' : (editId ? '수정 완료' : '등록')}
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
