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

const FILE_LABELS = { image: '이미지', video: '영상', stl: 'STL', wiring: '배선도', firmware: '펌웨어' };

export default function ProjectDetail() {
  const { id } = useParams();
  const navigate = useNavigate();
  const [project, setProject] = useState(null);
  const [loading, setLoading] = useState(true);
  const [imgIdx, setImgIdx]   = useState(0);

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

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

  const images   = project.files.filter(f => f.fileType === 'image');
  const others   = project.files.filter(f => f.fileType !== 'image');
  const product  = project.product;

  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, flexWrap: 'wrap' }}>
                  {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 }}>{project.title}</h1>
          <div className="text-muted" style={{ fontSize: 13, marginBottom: 20 }}>
            by {project.user.nickname} · 난이도 {'⭐'.repeat(project.difficultyLevel)}
          </div>

          <div className="divider" />
          <h3 style={{ marginBottom: 12 }}>프로젝트 설명</h3>
          <p style={{ color: 'var(--text2)', lineHeight: 1.8, whiteSpace: 'pre-wrap' }}>{project.description}</p>

          {/* 필요 부품 */}
          {project.requiredParts?.length > 0 && (
            <>
              <div className="divider" />
              <h3 style={{ marginBottom: 12 }}>필요 부품</h3>
              <div className="table-wrap">
                <table>
                  <thead><tr><th>부품명</th><th>수량</th><th>구매처</th></tr></thead>
                  <tbody>
                    {project.requiredParts.map((p, i) => (
                      <tr key={i}>
                        <td>{p.name}</td>
                        <td>{p.quantity || '-'}</td>
                        <td>{p.link ? <a href={p.link} target="_blank" rel="noreferrer">링크</a> : '-'}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </>
          )}

          {/* 첨부 파일 */}
          {others.length > 0 && (
            <>
              <div className="divider" />
              <h3 style={{ marginBottom: 12 }}>첨부 파일</h3>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {others.map(f => (
                  <a key={f.id} href={f.url} target="_blank" rel="noreferrer"
                    className="card" style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 14px' }}>
                    <span style={{ fontSize: 20 }}>
                      {f.fileType === 'stl' ? '🖨️' : f.fileType === 'wiring' ? '🔌' : f.fileType === 'video' ? '🎬' : '📄'}
                    </span>
                    <div>
                      <div style={{ fontSize: 13 }}>{f.originalName || FILE_LABELS[f.fileType] || f.fileType}</div>
                      <div className="text-muted" style={{ fontSize: 12 }}>{(f.fileSize / 1024).toFixed(1)} KB</div>
                    </div>
                  </a>
                ))}
              </div>
            </>
          )}
        </div>

        {/* 오른쪽 — 구매 */}
        <div>
          {product && product.isOnSale ? (
            <div className="card" style={{ position: 'sticky', top: 80 }}>
              <div style={{ fontSize: 28, fontWeight: 700, color: 'var(--accent2)', marginBottom: 8 }}>
                ₩{product.price.toLocaleString()}
              </div>
              <div className="text-muted" style={{ fontSize: 13, marginBottom: 20 }}>
                판매 {product.totalSales.toLocaleString()}건
              </div>
              <Link to={`/shop/${product.id}`} className="btn btn-primary" style={{ width: '100%', justifyContent: 'center' }}>
                구매하기 →
              </Link>
              <p className="text-muted mt-8" style={{ fontSize: 12, textAlign: 'center' }}>
                구매 후 브라우저에서 바로 플래시 가능
              </p>
            </div>
          ) : (
            <div className="card">
              <p className="text-muted text-center">이 프로젝트는 현재 판매 중이 아닙니다.</p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
