import { useEffect, useState } from 'react';

const API = '/api/admin/members';
const token = () => localStorage.getItem('admin_token');
const headers = () => ({ Authorization: `Bearer ${token()}`, 'Content-Type': 'application/json' });

export default function AdminMember() {
  const [data,    setData]    = useState({ content: [], totalElements: 0 });
  const [page,    setPage]    = useState(0);
  const [keyword, setKeyword] = useState('');
  const [search,  setSearch]  = useState('');
  const [loading, setLoading] = useState(false);

  const load = async (p = page, kw = search) => {
    setLoading(true);
    try {
      const qs = new URLSearchParams({ page: p, size: 20, ...(kw && { keyword: kw }) });
      const res = await fetch(`${API}?${qs}`, { headers: headers() });
      if (res.ok) setData(await res.json());
    } finally { setLoading(false); }
  };

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

  const handleSearch = e => { e.preventDefault(); setPage(0); setSearch(keyword); };

  const toggleStatus = async (id, active) => {
    if (!confirm(`${active ? '비활성화' : '활성화'}하시겠습니까?`)) return;
    await fetch(`${API}/${id}/status`, {
      method: 'PATCH', headers: headers(),
      body: JSON.stringify({ active: !active }),
    });
    load();
  };

  const deleteMember = async id => {
    if (!confirm('삭제하면 복구할 수 없습니다. 삭제하시겠습니까?')) return;
    await fetch(`${API}/${id}`, { method: 'DELETE', headers: headers() });
    load();
  };

  const members = data.content || [];
  const total   = data.totalElements || 0;
  const totalPages = Math.ceil(total / 20);

  return (
    <div>
      {/* 헤더 */}
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:24 }}>
        <div>
          <h2 style={{ fontSize:20, fontWeight:700, color:'#1e293b', margin:0 }}>회원 관리</h2>
          <p style={{ fontSize:13, color:'#64748b', margin:'4px 0 0' }}>총 {total.toLocaleString()}명</p>
        </div>
        <form onSubmit={handleSearch} style={{ display:'flex', gap:8 }}>
          <input
            value={keyword}
            onChange={e => setKeyword(e.target.value)}
            placeholder="이름 / 이메일 / 소속 검색"
            style={{ padding:'8px 14px', border:'1px solid #e2e8f0', borderRadius:8,
                     fontSize:13, width:240, outline:'none' }}
          />
          <button type="submit"
            style={{ padding:'8px 16px', background:'#1a5fd8', color:'#fff',
                     border:'none', borderRadius:8, fontSize:13, cursor:'pointer' }}>
            검색
          </button>
        </form>
      </div>

      {/* 테이블 */}
      <div style={{ background:'#fff', border:'1px solid #e2e8f0', borderRadius:10, overflow:'hidden' }}>
        <table style={{ width:'100%', borderCollapse:'collapse', fontSize:13 }}>
          <thead>
            <tr style={{ background:'#f8fafc' }}>
              {['ID','이름','이메일','연락처','소속','가입일','상태','액션'].map(h => (
                <th key={h} style={{ padding:'10px 14px', textAlign:'left', fontWeight:600,
                                     color:'#475569', borderBottom:'1px solid #e2e8f0' }}>
                  {h}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr><td colSpan={8} style={{ padding:40, textAlign:'center', color:'#94a3b8' }}>
                로딩 중...
              </td></tr>
            ) : members.length === 0 ? (
              <tr><td colSpan={8} style={{ padding:40, textAlign:'center', color:'#94a3b8' }}>
                {search ? '검색 결과가 없습니다.' : '등록된 회원이 없습니다.'}
              </td></tr>
            ) : members.map(m => (
              <tr key={m.id} style={{ borderBottom:'1px solid #f1f5f9' }}>
                <td style={{ padding:'10px 14px', color:'#94a3b8' }}>#{m.id}</td>
                <td style={{ padding:'10px 14px', fontWeight:600, color:'#1e293b' }}>{m.name}</td>
                <td style={{ padding:'10px 14px', color:'#475569' }}>{m.email}</td>
                <td style={{ padding:'10px 14px', color:'#64748b' }}>{m.phone || '-'}</td>
                <td style={{ padding:'10px 14px', color:'#64748b' }}>{m.company || '-'}</td>
                <td style={{ padding:'10px 14px', color:'#64748b', fontSize:12 }}>
                  {m.createdAt ? new Date(m.createdAt).toLocaleDateString('ko-KR') : '-'}
                </td>
                <td style={{ padding:'10px 14px' }}>
                  <span style={{
                    padding:'3px 10px', borderRadius:12, fontSize:11, fontWeight:700,
                    background: m.active ? '#dcfce7' : '#fee2e2',
                    color:      m.active ? '#16a34a' : '#dc2626',
                  }}>
                    {m.active ? '활성' : '비활성'}
                  </span>
                </td>
                <td style={{ padding:'10px 14px' }}>
                  <div style={{ display:'flex', gap:6 }}>
                    <button onClick={() => toggleStatus(m.id, m.active)}
                      style={{ padding:'4px 10px', fontSize:11, borderRadius:6, cursor:'pointer',
                               background: m.active ? '#fef3c7' : '#dcfce7',
                               color:      m.active ? '#92400e' : '#166534',
                               border:'none' }}>
                      {m.active ? '비활성화' : '활성화'}
                    </button>
                    <button onClick={() => deleteMember(m.id)}
                      style={{ padding:'4px 10px', fontSize:11, borderRadius:6, cursor:'pointer',
                               background:'#fef2f2', color:'#dc2626', border:'none' }}>
                      삭제
                    </button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* 페이지네이션 */}
      {totalPages > 1 && (
        <div style={{ display:'flex', gap:6, justifyContent:'center', marginTop:20 }}>
          <button onClick={() => setPage(p => Math.max(0, p-1))} disabled={page===0}
            style={{ padding:'6px 14px', borderRadius:6, border:'1px solid #e2e8f0',
                     background:'#fff', cursor:'pointer', fontSize:13 }}>
            이전
          </button>
          {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
            const p = Math.max(0, Math.min(page - 2, totalPages - 5)) + i;
            return (
              <button key={p} onClick={() => setPage(p)}
                style={{ padding:'6px 12px', borderRadius:6, fontSize:13, cursor:'pointer',
                         border: p===page ? 'none' : '1px solid #e2e8f0',
                         background: p===page ? '#1a5fd8' : '#fff',
                         color:      p===page ? '#fff'    : '#475569' }}>
                {p+1}
              </button>
            );
          })}
          <button onClick={() => setPage(p => Math.min(totalPages-1, p+1))} disabled={page===totalPages-1}
            style={{ padding:'6px 14px', borderRadius:6, border:'1px solid #e2e8f0',
                     background:'#fff', cursor:'pointer', fontSize:13 }}>
            다음
          </button>
        </div>
      )}
    </div>
  );
}
