import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import api from '../api/client';

const DIFFICULTY = ['', '⭐ 입문', '⭐⭐ 초급', '⭐⭐⭐ 중급', '⭐⭐⭐⭐ 고급', '⭐⭐⭐⭐⭐ 전문가'];

export default function Projects() {
  const [data, setData]         = useState({ projects: [], total: 0, pages: 1 });
  const [page, setPage]         = useState(1);
  const [difficulty, setDiff]   = useState('');
  const [loading, setLoading]   = useState(true);
  const navigate = useNavigate();

  useEffect(() => {
    setLoading(true);
    const params = new URLSearchParams({ page, limit: 18 });
    if (difficulty) params.set('difficulty', difficulty);
    api.get(`/projects?${params}`)
      .then(r => setData(r.data))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [page, difficulty]);

  return (
    <div className="container page">
      <div className="flex items-center justify-between" style={{ marginBottom: 20 }}>
        <h2 style={{ fontSize: 20 }}>ESP32 프로젝트</h2>
        <select style={{ width: 160 }} value={difficulty} onChange={e => { setDiff(e.target.value); setPage(1); }}>
          <option value="">난이도 전체</option>
          {[1,2,3,4,5].map(d => <option key={d} value={d}>{DIFFICULTY[d]}</option>)}
        </select>
      </div>

      {loading ? <div className="spinner" /> : (
        <>
          <div className="card-grid">
            {data.projects.map(p => (
              <div key={p.id} className="project-card" onClick={() => navigate(`/projects/${p.id}`)}>
                {p.files[0]
                  ? <img src={p.files[0].thumbnailUrl || p.files[0].url} alt={p.title} />
                  : <div style={{ height: 180, background: 'var(--bg3)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--text2)' }}>이미지 없음</div>
                }
                <div className="project-card-body">
                  <div className="project-card-title">{p.title}</div>
                  <div className="project-card-meta">
                    <span>{p.user.nickname}</span>
                    <span>{DIFFICULTY[p.difficultyLevel]}</span>
                    {p.product && (
                      <span style={{ marginLeft: 'auto', color: 'var(--accent2)', fontWeight: 600 }}>
                        ₩{p.product.price.toLocaleString()}
                      </span>
                    )}
                  </div>
                </div>
              </div>
            ))}
          </div>

          {data.projects.length === 0 && (
            <div className="card text-center" style={{ padding: 48 }}>
              <p className="text-muted">등록된 프로젝트가 없습니다.</p>
            </div>
          )}

          {data.pages > 1 && (
            <div className="pagination">
              <button disabled={page <= 1} onClick={() => setPage(p => p - 1)}>이전</button>
              {Array.from({ length: data.pages }, (_, i) => (
                <button key={i + 1} className={page === i + 1 ? 'active' : ''} onClick={() => setPage(i + 1)}>
                  {i + 1}
                </button>
              ))}
              <button disabled={page >= data.pages} onClick={() => setPage(p => p + 1)}>다음</button>
            </div>
          )}
        </>
      )}
    </div>
  );
}
