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

export default function ProjectNew() {
  const navigate = useNavigate();
  const [form, setForm] = useState({
    title: '', description: '', difficultyLevel: 3, requiredParts: [],
  });
  const [partRow, setPartRow]     = useState({ name: '', quantity: '', link: '' });
  const [files, setFiles]         = useState([]);
  const [fileType, setFileType]   = useState('image');
  const [dragging, setDragging]   = useState(false);
  const [error, setError]         = useState('');
  const [step, setStep]           = useState(1); // 1:기본정보, 2:파일, 3:완료
  const [saving, setSaving]       = useState(false);
  const [projectId, setProjectId] = useState(null);
  const fileRef = useRef();

  function addPart() {
    if (!partRow.name) return;
    setForm(f => ({ ...f, requiredParts: [...f.requiredParts, { ...partRow }] }));
    setPartRow({ name: '', quantity: '', link: '' });
  }
  function removePart(i) {
    setForm(f => ({ ...f, requiredParts: f.requiredParts.filter((_, idx) => idx !== i) }));
  }

  async function handleStep1(e) {
    e.preventDefault();
    setError('');
    setSaving(true);
    try {
      const { data } = await api.post('/projects', {
        title: form.title,
        description: form.description,
        difficultyLevel: form.difficultyLevel,
        requiredParts: form.requiredParts,
      });
      setProjectId(data.id);
      setStep(2);
    } catch (err) {
      setError(err.response?.data?.error || '저장 실패');
    } finally {
      setSaving(false);
    }
  }

  async function handleUpload() {
    if (!files.length) { setStep(3); return; }
    setError('');
    setSaving(true);
    try {
      const fd = new FormData();
      fd.append('fileType', fileType);
      files.forEach(f => fd.append('files', f));
      await api.post(`/projects/${projectId}/files`, fd, {
        headers: { 'Content-Type': 'multipart/form-data' },
      });
      setFiles([]);
      setStep(3);
    } catch (err) {
      setError(err.response?.data?.error || '업로드 실패');
    } finally {
      setSaving(false);
    }
  }

  async function submitForReview() {
    setSaving(true);
    try {
      await api.post(`/projects/${projectId}/submit`);
      navigate('/dashboard');
    } catch (err) {
      setError(err.response?.data?.error || '제출 실패');
    } finally {
      setSaving(false);
    }
  }

  function onDrop(e) {
    e.preventDefault();
    setDragging(false);
    setFiles(prev => [...prev, ...Array.from(e.dataTransfer.files)]);
  }

  return (
    <div className="container page" style={{ maxWidth: 700 }}>
      {/* 스텝 표시 */}
      <div style={{ display: 'flex', gap: 8, marginBottom: 32 }}>
        {['기본 정보', '파일 업로드', '검토 제출'].map((label, i) => (
          <div key={i} style={{ flex: 1, textAlign: 'center', padding: '8px 0', borderRadius: 'var(--radius)',
            background: step === i + 1 ? 'var(--accent)' : step > i + 1 ? 'var(--bg3)' : 'var(--bg2)',
            border: '1px solid var(--border)', color: step === i + 1 ? '#fff' : 'var(--text2)', fontSize: 13 }}>
            {i + 1}. {label}
          </div>
        ))}
      </div>

      {error && <div className="alert alert-error">{error}</div>}

      {/* 스텝 1 */}
      {step === 1 && (
        <form className="card" onSubmit={handleStep1}>
          <h3 style={{ marginBottom: 20 }}>기본 정보</h3>
          <div className="form-group">
            <label>프로젝트 제목 *</label>
            <input required value={form.title} onChange={e => setForm(f => ({ ...f, title: e.target.value }))}
              placeholder="예: ESP32-S3 CAN FD 로거" />
          </div>
          <div className="form-group">
            <label>설명 *</label>
            <textarea required value={form.description}
              onChange={e => setForm(f => ({ ...f, description: e.target.value }))}
              placeholder="프로젝트 목적, 기능, 특징을 설명해주세요" rows={6} />
          </div>
          <div className="form-group">
            <label>난이도</label>
            <select value={form.difficultyLevel} onChange={e => setForm(f => ({ ...f, difficultyLevel: parseInt(e.target.value) }))}>
              {[1,2,3,4,5].map(d => <option key={d} value={d}>{d} — {['입문','초급','중급','고급','전문가'][d-1]}</option>)}
            </select>
          </div>

          {/* 필요 부품 */}
          <div className="form-group">
            <label>필요 부품 (선택)</label>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 80px 1fr auto', gap: 8, marginBottom: 8 }}>
              <input placeholder="부품명" value={partRow.name} onChange={e => setPartRow(p => ({ ...p, name: e.target.value }))} />
              <input placeholder="수량" value={partRow.quantity} onChange={e => setPartRow(p => ({ ...p, quantity: e.target.value }))} />
              <input placeholder="알리/쿠팡 링크" value={partRow.link} onChange={e => setPartRow(p => ({ ...p, link: e.target.value }))} />
              <button type="button" className="btn btn-outline btn-sm" onClick={addPart}>추가</button>
            </div>
            {form.requiredParts.map((p, i) => (
              <div key={i} style={{ display: 'flex', gap: 8, alignItems: 'center', fontSize: 13, padding: '4px 0' }}>
                <span style={{ flex: 1 }}>{p.name}</span>
                <span className="text-muted">{p.quantity}</span>
                {p.link && <a href={p.link} target="_blank" rel="noreferrer" style={{ fontSize: 12 }}>링크</a>}
                <button type="button" className="btn btn-danger btn-sm" onClick={() => removePart(i)}>✕</button>
              </div>
            ))}
          </div>

          <button className="btn btn-primary" disabled={saving}>
            {saving ? '저장 중...' : '다음 단계 →'}
          </button>
        </form>
      )}

      {/* 스텝 2 */}
      {step === 2 && (
        <div className="card">
          <h3 style={{ marginBottom: 20 }}>파일 업로드</h3>
          <div className="form-group">
            <label>파일 종류</label>
            <select value={fileType} onChange={e => setFileType(e.target.value)}>
              <option value="image">이미지 (jpg, png, webp)</option>
              <option value="video">영상 (mp4, mov)</option>
              <option value="wiring">배선도 (jpg, png, pdf)</option>
              <option value="stl">3D 케이스 STL</option>
              <option value="firmware">펌웨어 (.bin)</option>
            </select>
          </div>
          <div className={`dropzone${dragging ? ' over' : ''}`}
            onDragOver={e => { e.preventDefault(); setDragging(true); }}
            onDragLeave={() => setDragging(false)}
            onDrop={onDrop}
            onClick={() => fileRef.current.click()}>
            <input ref={fileRef} type="file" multiple hidden
              onChange={e => setFiles(prev => [...prev, ...Array.from(e.target.files)])} />
            <p>파일을 드래그하거나 클릭하여 선택</p>
            <p>이미지 최대 20MB · 영상 최대 500MB · 펌웨어 최대 64MB</p>
          </div>
          {files.length > 0 && (
            <ul style={{ marginTop: 12, fontSize: 13, color: 'var(--text2)' }}>
              {files.map((f, i) => (
                <li key={i} style={{ display: 'flex', justifyContent: 'space-between', padding: '4px 0' }}>
                  <span>{f.name}</span>
                  <span>{(f.size / 1024 / 1024).toFixed(1)} MB</span>
                </li>
              ))}
            </ul>
          )}
          <div style={{ display: 'flex', gap: 8, marginTop: 20 }}>
            <button className="btn btn-outline" onClick={() => setStep(1)}>← 이전</button>
            <button className="btn btn-primary" onClick={handleUpload} disabled={saving}>
              {saving ? '업로드 중...' : files.length > 0 ? '업로드 후 다음 →' : '건너뛰기 →'}
            </button>
          </div>
        </div>
      )}

      {/* 스텝 3 */}
      {step === 3 && (
        <div className="card text-center" style={{ padding: 48 }}>
          <div style={{ fontSize: 48, marginBottom: 16 }}>📋</div>
          <h3 style={{ marginBottom: 12 }}>관리자 검토 요청</h3>
          <p className="text-muted" style={{ marginBottom: 24 }}>
            프로젝트 정보와 파일이 저장되었습니다.<br />
            관리자 검토 요청을 보내면 승인 후 판매가 시작됩니다.
          </p>
          <div style={{ display: 'flex', gap: 8, justifyContent: 'center' }}>
            <button className="btn btn-outline" onClick={() => navigate('/dashboard')}>나중에</button>
            <button className="btn btn-primary" onClick={submitForReview} disabled={saving}>
              {saving ? '제출 중...' : '검토 요청 제출'}
            </button>
          </div>
          {error && <div className="alert alert-error" style={{ marginTop: 16 }}>{error}</div>}
        </div>
      )}
    </div>
  );
}
