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 STATUS_LABEL = { PENDING: '미답변', ANSWERED: '답변완료', CLOSED: '종결' };
const STATUS_BADGE = { PENDING: 'badge-red', ANSWERED: 'badge-green', CLOSED: 'badge-gray' };

export default function AdminInquiry() {
  const [page, setPage] = useState(0);
  const [filter, setFilter] = useState('');
  const [data, setData] = useState({ content: [], totalPages: 0, totalElements: 0 });
  const [selected, setSelected] = useState(null);
  const [toast, setToast] = useState(null);

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

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

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

  const handleStatus = async (id, status) => {
    const res = await authFetch(`/api/admin/inquiries/${id}/status`, {
      method: 'PATCH', body: JSON.stringify({ status }),
    });
    if (res.ok) {
      load();
      if (selected?.id === id) setSelected(p => ({ ...p, status }));
      showToast('상태가 변경되었습니다.');
    }
  };

  const openDetail = async (id) => {
    const res = await authFetch(`/api/admin/inquiries/${id}`);
    if (res.ok) setSelected(await res.json());
  };

  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>
          <select className="admin-select" value={filter} onChange={e => { setFilter(e.target.value); setPage(0); }}>
            <option value="">전체 상태</option>
            <option value="PENDING">미답변</option>
            <option value="ANSWERED">답변완료</option>
            <option value="CLOSED">종결</option>
          </select>
        </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((q, i) => (
                <tr key={q.id} style={{ cursor: 'pointer' }}>
                  <td style={{ color: '#94a3b8', fontSize: 12 }}>{data.totalElements - page * 10 - i}</td>
                  <td>{q.name}</td>
                  <td onClick={() => openDetail(q.id)}>
                    <span className="truncate" style={{ display: 'block', color: '#4f6ef7', cursor: 'pointer' }}>{q.subject}</span>
                  </td>
                  <td><span className="badge badge-blue">{q.category || '기타'}</span></td>
                  <td><span className={`badge ${STATUS_BADGE[q.status] || 'badge-gray'}`}>{STATUS_LABEL[q.status] || q.status}</span></td>
                  <td style={{ fontSize: 12, color: '#94a3b8' }}>{q.createdAt?.slice(0, 10)}</td>
                  <td>
                    <div className="action-btns">
                      {q.status === 'PENDING' && (
                        <button className="btn btn-outline btn-sm" onClick={() => handleStatus(q.id, 'ANSWERED')}>답변완료</button>
                      )}
                      {q.status !== 'CLOSED' && (
                        <button className="btn btn-outline btn-sm" onClick={() => handleStatus(q.id, 'CLOSED')}>종결</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: Math.min(data.totalPages, 7) }, (_, 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>

      {selected && (
        <div className="modal-backdrop" onClick={e => e.target === e.currentTarget && setSelected(null)}>
          <div className="modal">
            <div className="modal-header">
              <h3>문의 상세</h3>
              <button onClick={() => setSelected(null)}>✕</button>
            </div>
            <div className="modal-body">
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 16 }}>
                {[['이름', selected.name], ['이메일', selected.email], ['연락처', selected.phone || '-'], ['유형', selected.category || '기타']].map(([l, v]) => (
                  <div key={l}>
                    <div style={{ fontSize: 11, fontWeight: 600, color: '#64748b', marginBottom: 3, textTransform: 'uppercase' }}>{l}</div>
                    <div style={{ fontSize: 13.5 }}>{v}</div>
                  </div>
                ))}
              </div>
              <div style={{ marginBottom: 12 }}>
                <div style={{ fontSize: 11, fontWeight: 600, color: '#64748b', marginBottom: 4, textTransform: 'uppercase' }}>제목</div>
                <div style={{ fontWeight: 600, fontSize: 15 }}>{selected.subject}</div>
              </div>
              <div>
                <div style={{ fontSize: 11, fontWeight: 600, color: '#64748b', marginBottom: 6, textTransform: 'uppercase' }}>내용</div>
                <div style={{ background: '#f8fafc', borderRadius: 8, padding: '14px 16px', fontSize: 13.5, lineHeight: 1.7, whiteSpace: 'pre-wrap', border: '1px solid #e2e8f0' }}>
                  {selected.content}
                </div>
              </div>
              <div style={{ marginTop: 16, display: 'flex', alignItems: 'center', gap: 8 }}>
                <span style={{ fontSize: 12, color: '#64748b' }}>접수일: {selected.createdAt?.slice(0, 16)}</span>
                <span className={`badge ${STATUS_BADGE[selected.status] || 'badge-gray'}`}>{STATUS_LABEL[selected.status]}</span>
              </div>
            </div>
            <div className="modal-footer">
              {selected.status === 'PENDING' && (
                <button className="btn btn-primary" onClick={() => handleStatus(selected.id, 'ANSWERED')}>답변완료 처리</button>
              )}
              {selected.status !== 'CLOSED' && (
                <button className="btn btn-outline" onClick={() => handleStatus(selected.id, 'CLOSED')}>종결</button>
              )}
              <button className="btn btn-outline" onClick={() => setSelected(null)}>닫기</button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
