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 = { category: 'GUARDiA ITSM', question: '', answer: '', orderNum: 0, visible: true };
const CATS  = ['GUARDiA ITSM', '도입·계약', '기술 지원', '일반'];

export default function AdminFAQ() {
  const [list, setList]   = useState([]);
  const [modal, setModal] = useState(null);   // null | 'add' | 'edit'
  const [form, setForm]   = useState(EMPTY);
  const [editId, setEditId] = useState(null);
  const [filterCat, setFilterCat] = useState('');

  const load = useCallback(() => {
    authFetch('/api/admin/faq').then(r => r.json()).then(setList).catch(() => {});
  }, []);

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

  const open = (item = null) => {
    if (item) { setForm({ ...item }); setEditId(item.id); setModal('edit'); }
    else       { setForm(EMPTY);      setEditId(null);    setModal('add');  }
  };

  const save = async () => {
    const url    = modal === 'edit' ? `/api/admin/faq/${editId}` : '/api/admin/faq';
    const method = modal === 'edit' ? 'PUT' : 'POST';
    await authFetch(url, { method, body: JSON.stringify(form) });
    setModal(null); load();
  };

  const del = async (id) => {
    if (!window.confirm('삭제하시겠습니까?')) return;
    await authFetch(`/api/admin/faq/${id}`, { method: 'DELETE' });
    load();
  };

  const filtered = filterCat ? list.filter(f => f.category === filterCat) : list;

  return (
    <div style={{ padding: '24px' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
        <h2 style={{ fontSize: '20px', fontWeight: '700' }}>FAQ 관리</h2>
        <button onClick={() => open()} style={{ background: 'var(--primary)', color: '#fff', border: 'none', padding: '8px 20px', borderRadius: '6px', cursor: 'pointer', fontWeight: '600' }}>
          + FAQ 추가
        </button>
      </div>

      {/* 카테고리 필터 */}
      <div style={{ display: 'flex', gap: '8px', marginBottom: '16px', flexWrap: 'wrap' }}>
        {['전체', ...CATS].map(c => (
          <button key={c} onClick={() => setFilterCat(c === '전체' ? '' : c)}
            style={{ padding: '4px 14px', borderRadius: '20px', border: '1px solid', cursor: 'pointer', fontWeight: '500', fontSize: '13px',
              background: (c === '전체' ? !filterCat : filterCat === c) ? 'var(--primary)' : '#fff',
              color:      (c === '전체' ? !filterCat : filterCat === c) ? '#fff' : 'var(--gray-600)',
              borderColor:(c === '전체' ? !filterCat : filterCat === c) ? 'var(--primary)' : 'var(--gray-200)' }}>
            {c}
          </button>
        ))}
      </div>

      {/* FAQ 목록 */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
        {filtered.length === 0 ? (
          <div style={{ textAlign: 'center', padding: '60px', color: 'var(--gray-400)' }}>등록된 FAQ가 없습니다.</div>
        ) : filtered.map(f => (
          <div key={f.id} style={{ background: '#fff', border: '1px solid var(--gray-200)', borderRadius: '8px', padding: '16px 20px' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: '12px' }}>
              <div style={{ flex: 1 }}>
                <span style={{ fontSize: '11px', background: 'var(--primary-light)', color: 'var(--primary)', padding: '2px 8px', borderRadius: '10px', fontWeight: '600' }}>{f.category}</span>
                <p style={{ fontWeight: '600', margin: '8px 0 4px', fontSize: '14px' }}>Q. {f.question}</p>
                <p style={{ fontSize: '13px', color: 'var(--gray-600)', lineHeight: '1.6' }}>A. {f.answer}</p>
              </div>
              <div style={{ display: 'flex', gap: '6px', flexShrink: 0 }}>
                <span style={{ fontSize: '11px', color: f.visible ? '#059669' : 'var(--gray-400)', fontWeight: '600' }}>{f.visible ? '공개' : '비공개'}</span>
                <button onClick={() => open(f)} style={{ padding: '4px 12px', border: '1px solid var(--gray-200)', borderRadius: '4px', cursor: 'pointer', fontSize: '12px' }}>수정</button>
                <button onClick={() => del(f.id)} style={{ padding: '4px 12px', background: '#fee2e2', color: '#dc2626', border: 'none', borderRadius: '4px', cursor: 'pointer', fontSize: '12px' }}>삭제</button>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* 모달 */}
      {modal && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.5)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000 }}>
          <div style={{ background: '#fff', borderRadius: '12px', padding: '32px', width: '600px', maxHeight: '90vh', overflowY: 'auto' }}>
            <h3 style={{ fontSize: '18px', fontWeight: '700', marginBottom: '24px' }}>{modal === 'edit' ? 'FAQ 수정' : 'FAQ 추가'}</h3>

            <label style={{ display: 'block', marginBottom: '16px' }}>
              <span style={{ fontSize: '13px', fontWeight: '600', color: 'var(--gray-700)', display: 'block', marginBottom: '6px' }}>카테고리</span>
              <select value={form.category} onChange={e => setForm(p => ({ ...p, category: e.target.value }))}
                style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--gray-200)', borderRadius: '6px', fontSize: '14px' }}>
                {CATS.map(c => <option key={c}>{c}</option>)}
              </select>
            </label>

            <label style={{ display: 'block', marginBottom: '16px' }}>
              <span style={{ fontSize: '13px', fontWeight: '600', color: 'var(--gray-700)', display: 'block', marginBottom: '6px' }}>질문 (Q)</span>
              <input value={form.question} onChange={e => setForm(p => ({ ...p, question: e.target.value }))}
                placeholder="질문을 입력하세요"
                style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--gray-200)', borderRadius: '6px', fontSize: '14px' }} />
            </label>

            <label style={{ display: 'block', marginBottom: '16px' }}>
              <span style={{ fontSize: '13px', fontWeight: '600', color: 'var(--gray-700)', display: 'block', marginBottom: '6px' }}>답변 (A)</span>
              <textarea value={form.answer} onChange={e => setForm(p => ({ ...p, answer: e.target.value }))}
                rows={5} placeholder="답변을 입력하세요"
                style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--gray-200)', borderRadius: '6px', fontSize: '14px', resize: 'vertical' }} />
            </label>

            <div style={{ display: 'flex', gap: '12px', marginBottom: '16px' }}>
              <label style={{ display: 'flex', alignItems: 'center', gap: '8px', cursor: 'pointer' }}>
                <input type="checkbox" checked={form.visible} onChange={e => setForm(p => ({ ...p, visible: e.target.checked }))} />
                <span style={{ fontSize: '13px', fontWeight: '600' }}>공개</span>
              </label>
              <label style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                <span style={{ fontSize: '13px', fontWeight: '600' }}>순서</span>
                <input type="number" value={form.orderNum} min={0} onChange={e => setForm(p => ({ ...p, orderNum: +e.target.value }))}
                  style={{ width: '70px', padding: '4px 8px', border: '1px solid var(--gray-200)', borderRadius: '4px', fontSize: '14px' }} />
              </label>
            </div>

            <div style={{ display: 'flex', gap: '12px', justifyContent: 'flex-end' }}>
              <button onClick={() => setModal(null)} style={{ padding: '10px 24px', border: '1px solid var(--gray-200)', borderRadius: '6px', cursor: 'pointer' }}>취소</button>
              <button onClick={save} style={{ padding: '10px 24px', background: 'var(--primary)', color: '#fff', border: 'none', borderRadius: '6px', cursor: 'pointer', fontWeight: '600' }}>저장</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
