'use client'

import React, { useState } from 'react'
import { useRouter, useParams } from 'next/navigation'
import Link from 'next/link'
import { motion } from 'framer-motion'

export default function WriteReviewPage() {
  const { id } = useParams<{ id: string }>()
  const router = useRouter()
  const [rating, setRating] = useState(0)
  const [hovered, setHovered] = useState(0)
  const [body, setBody] = useState('')
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (rating === 0) { setError('Seleciona uma classificação.'); return }
    setError(null)
    setLoading(true)
    try {
      const res = await fetch(`/api/spots/${id}/reviews`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ rating, body }),
      })
      const data = await res.json()
      if (!res.ok) {
        setError(data.error?.formErrors?.[0] ?? data.error ?? 'Erro ao submeter review')
        return
      }
      router.push(`/spots/${id}?reviewed=true`)
    } catch {
      setError('Erro de ligação. Tenta de novo.')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div style={{ minHeight: '100vh', background: 'var(--ov-cloud)', display: 'flex', alignItems: 'flex-start', justifyContent: 'center', padding: 'var(--ov-space-10) var(--ov-space-6)' }}>
      <motion.div
        initial={{ opacity: 0, y: 16 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.3 }}
        style={{ background: 'var(--ov-white)', borderRadius: 'var(--ov-radius-xl)', boxShadow: 'var(--ov-shadow-lg)', padding: 'var(--ov-space-10)', width: '100%', maxWidth: 520 }}
      >
        <Link href={`/spots/${id}`} style={{ fontSize: 'var(--ov-fs-xs)', color: 'var(--ov-slate)', fontFamily: 'var(--ov-font-sans)', display: 'inline-flex', alignItems: 'center', gap: 4, marginBottom: 'var(--ov-space-5)', textDecoration: 'none' }}>
          ← Voltar ao spot
        </Link>

        <h1 style={{ fontFamily: 'var(--ov-font-display)', fontSize: 'var(--ov-fs-h2)', fontWeight: 800, color: 'var(--ov-navy)', margin: '0 0 var(--ov-space-2)' }}>
          Escrever Review
        </h1>
        <p style={{ fontFamily: 'var(--ov-font-sans)', fontSize: 'var(--ov-fs-sm)', color: 'var(--ov-slate)', margin: '0 0 var(--ov-space-8)' }}>
          A tua review será publicada após aprovação.
        </p>

        <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 'var(--ov-space-5)' }}>
          {error && <div className="auth-error" role="alert">{error}</div>}

          {/* Star picker */}
          <div className="form-group">
            <label className="form-label">Classificação *</label>
            <div style={{ display: 'flex', gap: 8, marginTop: 4 }} role="group" aria-label="Classificação em estrelas">
              {[1, 2, 3, 4, 5].map((star) => (
                <button
                  key={star}
                  type="button"
                  aria-label={`${star} estrela${star > 1 ? 's' : ''}`}
                  onClick={() => setRating(star)}
                  onMouseEnter={() => setHovered(star)}
                  onMouseLeave={() => setHovered(0)}
                  style={{
                    background: 'none', border: 'none', cursor: 'pointer', padding: 0,
                    fontSize: 32, lineHeight: 1,
                    color: star <= (hovered || rating) ? '#F5A623' : 'var(--ov-line)',
                    transition: 'color 0.1s',
                  }}
                >
                  ★
                </button>
              ))}
            </div>
            {rating > 0 && (
              <p style={{ margin: '4px 0 0', fontSize: 'var(--ov-fs-xs)', color: 'var(--ov-slate)', fontFamily: 'var(--ov-font-sans)' }}>
                {['', 'Fraco', 'Razoável', 'Bom', 'Muito bom', 'Excelente'][rating]}
              </p>
            )}
          </div>

          <div className="form-group">
            <label className="form-label" htmlFor="body">Comentário *</label>
            <textarea
              id="body"
              className="form-input"
              value={body}
              onChange={(e) => setBody(e.target.value)}
              required
              minLength={10}
              maxLength={1000}
              rows={5}
              placeholder="Descreve a tua experiência neste local…"
              style={{ resize: 'vertical' }}
            />
            <p style={{ margin: '4px 0 0', fontSize: 'var(--ov-fs-xs)', color: 'var(--ov-slate)', fontFamily: 'var(--ov-font-sans)', textAlign: 'right' }}>
              {body.length}/1000
            </p>
          </div>

          <button
            type="submit"
            disabled={loading || rating === 0}
            style={{
              background: 'var(--ov-blue)', color: 'var(--ov-white)', border: 'none',
              borderRadius: 'var(--ov-radius-pill)', padding: '12px 24px',
              fontFamily: 'var(--ov-font-sans)', fontWeight: 700, fontSize: 'var(--ov-fs-body)',
              cursor: loading || rating === 0 ? 'not-allowed' : 'pointer',
              opacity: loading || rating === 0 ? 0.6 : 1,
              transition: 'opacity 0.15s',
            }}
          >
            {loading ? 'A enviar…' : 'Publicar Review'}
          </button>
        </form>
      </motion.div>
    </div>
  )
}
