import { useState } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { Star, PenLine } from 'lucide-react'
import { createReview } from '../api/client'
import { useShop } from '../store/shop'

export default function ReviewWrite() {
  const { productId } = useParams()
  const pid = Number(productId)
  const nav = useNavigate()
  const { custToken } = useShop()
  const [rating, setRating] = useState(5)
  const [title, setTitle] = useState('')
  const [content, setContent] = useState('')
  const [imageUrl, setImageUrl] = useState('')
  const [msg, setMsg] = useState('')

  if (!custToken) { nav('/account'); return null }

  const submit = async (e: React.FormEvent) => {
    e.preventDefault(); setMsg('')
    try {
      await createReview({ productId: pid, rating, title, content, imageUrl })
      setMsg('리뷰가 등록되었습니다.')
      setTimeout(() => nav(`/product/${pid}`), 800)
    } catch { setMsg('등록에 실패했습니다. (구매 이력이 필요할 수 있습니다)') }
  }

  return (
    <div className="max-w-lg mx-auto px-4 py-8">
      <div className="flex items-center gap-2 mb-6"><PenLine className="text-bloom" size={22} /><h1 className="font-serif text-2xl font-bold text-blush-900">리뷰 작성</h1></div>
      <form onSubmit={submit} className="bg-white rounded-2xl border border-blush-100/60 p-5 space-y-4">
        <div>
          <div className="text-sm font-medium mb-2">별점</div>
          <div className="flex gap-1">
            {[1, 2, 3, 4, 5].map(n => (
              <button key={n} type="button" onClick={() => setRating(n)} className="text-amber-400">
                <Star size={28} fill={n <= rating ? 'currentColor' : 'none'} />
              </button>
            ))}
          </div>
        </div>
        <input value={title} onChange={e => setTitle(e.target.value)} placeholder="제목" className="w-full px-3 py-2.5 rounded-xl border border-blush-100 text-sm outline-none focus:border-bloom" />
        <textarea value={content} onChange={e => setContent(e.target.value)} rows={5} required placeholder="상품은 어떠셨나요? 신선도, 배송, 디자인 등을 적어주세요." className="w-full px-3 py-2.5 rounded-xl border border-blush-100 text-sm outline-none focus:border-bloom" />
        <input value={imageUrl} onChange={e => setImageUrl(e.target.value)} placeholder="사진 URL (선택)" className="w-full px-3 py-2.5 rounded-xl border border-blush-100 text-sm outline-none focus:border-bloom" />
        {msg && <div className="text-sm text-leaf">{msg}</div>}
        <div className="flex gap-2">
          <button className="flex-1 bg-bloom text-white font-semibold py-3 rounded-full hover:bg-bloom2">등록</button>
          <button type="button" onClick={() => nav(-1)} className="px-6 border border-blush-100 rounded-full text-gray-600">취소</button>
        </div>
      </form>
    </div>
  )
}
