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

function Stars({ rating, count }) {
  if (!rating) return <span className="text-muted" style={{ fontSize: 12 }}>리뷰 없음</span>;
  return (
    <span style={{ fontSize: 12 }}>
      <span className="stars">{'★'.repeat(Math.round(rating))}</span>
      <span className="text-muted"> {rating} ({count})</span>
    </span>
  );
}

export default function Shop() {
  const [data, setData]   = useState({ products: [], total: 0, pages: 1 });
  const [page, setPage]   = useState(1);
  const [sort, setSort]   = useState('popular');
  const [loading, setLoading] = useState(true);
  const navigate = useNavigate();

  useEffect(() => {
    setLoading(true);
    api.get(`/products?page=${page}&limit=18&sort=${sort}`)
      .then(r => setData(r.data))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [page, sort]);

  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={sort} onChange={e => { setSort(e.target.value); setPage(1); }}>
          <option value="popular">인기순</option>
          <option value="newest">최신순</option>
          <option value="price_asc">가격 낮은순</option>
          <option value="price_desc">가격 높은순</option>
        </select>
      </div>

      {loading ? <div className="spinner" /> : (
        <>
          <div className="card-grid">
            {data.products.map(p => (
              <div key={p.id} className="project-card" onClick={() => navigate(`/shop/${p.id}`)}>
                {p.project.files[0]
                  ? <img src={p.project.files[0].thumbnailUrl || p.project.files[0].url} alt={p.project.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.project.title}</div>
                  <div style={{ fontSize: 12, color: 'var(--text2)', marginBottom: 8 }}>
                    by {p.project.user.nickname}
                  </div>
                  <div className="project-card-meta">
                    <Stars rating={p.avgRating} count={p.reviewCount} />
                    <span style={{ marginLeft: 'auto', color: 'var(--accent2)', fontWeight: 700, fontSize: 15 }}>
                      ₩{p.price.toLocaleString()}
                    </span>
                  </div>
                </div>
              </div>
            ))}
          </div>

          {data.products.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>
  );
}
