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

function Stars({ rating }) {
  return <span className="stars">{'★'.repeat(rating)}{'☆'.repeat(5 - rating)}</span>;
}

export default function ProductDetail() {
  const { id }    = useParams();
  const navigate  = useNavigate();
  const { user }  = useAuth();
  const [product, setProduct]   = useState(null);
  const [loading, setLoading]   = useState(true);
  const [imgIdx, setImgIdx]     = useState(0);

  useEffect(() => {
    api.get(`/products/${id}`)
      .then(r => setProduct(r.data))
      .catch(() => navigate('/shop'))
      .finally(() => setLoading(false));
  }, [id]);

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

  const images  = product.project.files.filter(f => f.fileType === 'image');
  const reviews = product.reviews || [];
  const avgRating = product.avgRating;

  return (
    <div className="container page">
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 340px', gap: 32 }}>
        {/* 왼쪽 */}
        <div>
          {images.length > 0 && (
            <div style={{ marginBottom: 24 }}>
              <img src={images[imgIdx].url} alt="" style={{ width: '100%', maxHeight: 480, objectFit: 'cover', borderRadius: 'var(--radius)', background: 'var(--bg3)' }} />
              {images.length > 1 && (
                <div style={{ display: 'flex', gap: 8, marginTop: 8 }}>
                  {images.map((img, i) => (
                    <img key={img.id} src={img.thumbnailUrl || img.url} alt=""
                      onClick={() => setImgIdx(i)}
                      style={{ width: 64, height: 64, objectFit: 'cover', borderRadius: 4, cursor: 'pointer', border: i === imgIdx ? '2px solid var(--accent)' : '2px solid transparent' }}
                    />
                  ))}
                </div>
              )}
            </div>
          )}

          <h1 style={{ fontSize: 24, marginBottom: 8 }}>{product.project.title}</h1>
          <div className="text-muted" style={{ fontSize: 13, marginBottom: 8 }}>
            by {product.project.user.nickname}
          </div>
          {avgRating && (
            <div style={{ marginBottom: 16 }}>
              <Stars rating={Math.round(avgRating)} />
              <span className="text-muted" style={{ fontSize: 13 }}> {avgRating} ({product.reviewCount}개 리뷰)</span>
            </div>
          )}

          <div className="divider" />
          <p style={{ color: 'var(--text2)', lineHeight: 1.8, whiteSpace: 'pre-wrap' }}>
            {product.project.description}
          </p>

          {/* 리뷰 */}
          {reviews.length > 0 && (
            <>
              <div className="divider" />
              <h3 style={{ marginBottom: 16 }}>구매자 리뷰</h3>
              {reviews.map(r => (
                <div key={r.id} className="card" style={{ marginBottom: 12 }}>
                  <div className="flex items-center gap-8" style={{ marginBottom: 8 }}>
                    <strong style={{ fontSize: 13 }}>{r.user.nickname}</strong>
                    <Stars rating={r.rating} />
                    <span className="text-muted" style={{ fontSize: 12, marginLeft: 'auto' }}>
                      {new Date(r.createdAt).toLocaleDateString('ko-KR')}
                    </span>
                  </div>
                  <div style={{ fontWeight: 600, marginBottom: 4 }}>{r.title}</div>
                  <p className="text-muted" style={{ fontSize: 13 }}>{r.content}</p>
                  {r.media?.length > 0 && (
                    <div style={{ display: 'flex', gap: 8, marginTop: 10, flexWrap: 'wrap' }}>
                      {r.media.map(m => (
                        m.mediaType === 'image'
                          ? <img key={m.id} src={m.thumbnailUrl || m.url} alt="" style={{ width: 80, height: 80, objectFit: 'cover', borderRadius: 4 }} />
                          : <a key={m.id} href={m.url} target="_blank" rel="noreferrer" className="btn btn-outline btn-sm">영상 보기</a>
                      ))}
                    </div>
                  )}
                </div>
              ))}
            </>
          )}
        </div>

        {/* 오른쪽 — 구매 패널 */}
        <div>
          <div className="card" style={{ position: 'sticky', top: 80 }}>
            <div style={{ fontSize: 30, fontWeight: 700, color: 'var(--accent2)', marginBottom: 4 }}>
              ₩{product.price.toLocaleString()}
            </div>
            <div className="text-muted" style={{ fontSize: 13, marginBottom: 20 }}>
              총 판매 {product.totalSales.toLocaleString()}건
            </div>

            {product.isOnSale ? (
              <>
                {user ? (
                  <button className="btn btn-primary" style={{ width: '100%', justifyContent: 'center', fontSize: 16 }}
                    onClick={() => alert('결제 기능은 2단계에서 구현됩니다')}>
                    구매하기
                  </button>
                ) : (
                  <button className="btn btn-primary" style={{ width: '100%', justifyContent: 'center' }}
                    onClick={() => navigate('/auth/login', { state: { from: `/shop/${id}` } })}>
                    로그인 후 구매
                  </button>
                )}
                <div className="divider" />
                <ul style={{ color: 'var(--text2)', fontSize: 13, paddingLeft: 16 }}>
                  <li>구매 즉시 플래시 토큰 발급</li>
                  <li>USB 연결 후 브라우저에서 플래시</li>
                  <li>플래시 완료 후 환불 불가</li>
                </ul>
              </>
            ) : (
              <div className="alert alert-warn">현재 판매 중지 상태입니다</div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
