import { useEffect, useState } from 'react';
import api from '../../api/client';

export default function AdminProjects() {
  const [pending, setPending]     = useState([]);
  const [selected, setSelected]   = useState(null);
  const [approveForm, setApproveForm] = useState({ price: '', commissionRate: '0.1' });
  const [rejectNote, setRejectNote] = useState('');
  const [loading, setLoading]     = useState(true);
  const [saving, setSaving]       = useState(false);
  const [msg, setMsg]             = useState('');

  useEffect(() => {
    api.get('/admin/projects/pending')
      .then(r => setPending(r.data))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  async function handleApprove() {
    if (!approveForm.price) { setMsg('판매가를 입력해주세요'); return; }
    setSaving(true);
    try {
      await api.post(`/admin/projects/${selected.id}/approve`, {
        price: parseInt(approveForm.price),
        commissionRate: parseFloat(approveForm.commissionRate),
      });
      setPending(p => p.filter(x => x.id !== selected.id));
      setSelected(null);
      setMsg('승인되었습니다');
    } catch (err) {
      setMsg(err.response?.data?.error || '오류 발생');
    } finally {
      setSaving(false);
    }
  }

  async function handleReject() {
    if (!rejectNote.trim()) { setMsg('반려 사유를 입력해주세요'); return; }
    setSaving(true);
    try {
      await api.post(`/admin/projects/${selected.id}/reject`, { adminNote: rejectNote });
      setPending(p => p.filter(x => x.id !== selected.id));
      setSelected(null);
      setRejectNote('');
      setMsg('반려 처리되었습니다');
    } catch (err) {
      setMsg(err.response?.data?.error || '오류 발생');
    } finally {
      setSaving(false);
    }
  }

  if (loading) return <div className="spinner" />;

  return (
    <div className="container page">
      <h2 style={{ marginBottom: 8 }}>프로젝트 승인 관리</h2>
      <p className="text-muted" style={{ marginBottom: 24 }}>검토 대기 중인 프로젝트: {pending.length}건</p>

      {msg && <div className="alert alert-info" onClick={() => setMsg('')}>{msg}</div>}

      {pending.length === 0 ? (
        <div className="card text-center" style={{ padding: 48 }}>
          <p className="text-muted">검토 대기 중인 프로젝트가 없습니다.</p>
        </div>
      ) : (
        <div style={{ display: 'grid', gridTemplateColumns: selected ? '1fr 1fr' : '1fr', gap: 20 }}>
          {/* 목록 */}
          <div>
            {pending.map(p => (
              <div key={p.id} className="card" style={{ marginBottom: 12, cursor: 'pointer', borderColor: selected?.id === p.id ? 'var(--accent)' : 'var(--border)' }}
                onClick={() => { setSelected(p); setApproveForm({ price: '', commissionRate: '0.1' }); setRejectNote(''); }}>
                <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
                  {p.files[0] && (
                    <img src={p.files[0].thumbnailUrl || p.files[0].url} alt=""
                      style={{ width: 80, height: 60, objectFit: 'cover', borderRadius: 4, flexShrink: 0 }} />
                  )}
                  <div>
                    <div style={{ fontWeight: 600 }}>{p.title}</div>
                    <div className="text-muted" style={{ fontSize: 12 }}>
                      by {p.user.nickname} · 파일 {p._count.files}개 ·{' '}
                      {new Date(p.updatedAt).toLocaleDateString('ko-KR')}
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>

          {/* 상세 / 승인 패널 */}
          {selected && (
            <div className="card" style={{ height: 'fit-content', position: 'sticky', top: 80 }}>
              <h3 style={{ marginBottom: 16 }}>{selected.title}</h3>
              <p className="text-muted" style={{ fontSize: 13, marginBottom: 16, maxHeight: 120, overflow: 'auto' }}>
                {selected.description}
              </p>

              <div className="divider" />
              <h4 style={{ marginBottom: 12 }}>승인</h4>
              <div className="form-group">
                <label>판매가 (원)</label>
                <input type="number" min="100" placeholder="예: 9900"
                  value={approveForm.price} onChange={e => setApproveForm(f => ({ ...f, price: e.target.value }))} />
              </div>
              <div className="form-group">
                <label>수수료율 (0.0 ~ 1.0)</label>
                <input type="number" min="0" max="1" step="0.01"
                  value={approveForm.commissionRate}
                  onChange={e => setApproveForm(f => ({ ...f, commissionRate: e.target.value }))} />
              </div>
              <button className="btn btn-success" onClick={handleApprove} disabled={saving} style={{ width: '100%', marginBottom: 12, justifyContent: 'center' }}>
                {saving ? '처리 중...' : '✓ 승인하기'}
              </button>

              <div className="divider" />
              <h4 style={{ marginBottom: 12 }}>반려</h4>
              <div className="form-group">
                <label>반려 사유</label>
                <textarea value={rejectNote} onChange={e => setRejectNote(e.target.value)} rows={3}
                  placeholder="수정이 필요한 내용을 구체적으로 작성해주세요" />
              </div>
              <button className="btn btn-danger" onClick={handleReject} disabled={saving} style={{ width: '100%', justifyContent: 'center' }}>
                {saving ? '처리 중...' : '✕ 반려하기'}
              </button>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
