'use client'

import React, { useState, useRef, KeyboardEvent, useCallback } from 'react'
import { useRouter } from 'next/navigation'
import { motion } from 'framer-motion'
import { Button } from '@/components/ui'
import { LocationPicker } from './LocationPicker'
import './spots.css'

interface SpotFormData {
  name: string
  description: string
  lat: string
  lng: string
  altitude: string
  difficulty: 'BEGINNER' | 'INTERMEDIATE' | 'ADVANCED'
}

const DIFFICULTIES = [
  { value: 'BEGINNER', label: 'Iniciante', desc: 'Espaço aberto, sem obstáculos' },
  { value: 'INTERMEDIATE', label: 'Intermédio', desc: 'Requer alguma experiência' },
  { value: 'ADVANCED', label: 'Avançado', desc: 'Piloto experiente necessário' },
] as const

const SUGGESTED_TAGS = ['praia', 'montanha', 'urbano', 'pôr-do-sol', 'costa', 'rural', 'parque', 'floresta']

export function SpotForm() {
  const router = useRouter()
  const tagInputRef = useRef<HTMLInputElement>(null)
  const [form, setForm] = useState<SpotFormData>({
    name: '', description: '', lat: '', lng: '', altitude: '', difficulty: 'BEGINNER',
  })
  const [tags, setTags] = useState<string[]>([])
  const [tagInput, setTagInput] = useState('')
  const [photos, setPhotos] = useState<File[]>([])
  const [photoPreviews, setPhotoPreviews] = useState<string[]>([])
  const [error, setError] = useState<string | null>(null)
  const [loading, setLoading] = useState(false)
  const photoInputRef = useRef<HTMLInputElement>(null)

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    setForm((f) => ({ ...f, [e.target.name]: e.target.value }))
  }

  const addTag = (val: string) => {
    const clean = val.trim().toLowerCase()
    if (clean && !tags.includes(clean) && tags.length < 8) {
      setTags((t) => [...t, clean])
    }
    setTagInput('')
  }

  const removeTag = (tag: string) => setTags((t) => t.filter((x) => x !== tag))

  const handleTagKey = (e: KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter' || e.key === ',') {
      e.preventDefault()
      addTag(tagInput)
    } else if (e.key === 'Backspace' && !tagInput && tags.length > 0) {
      setTags((t) => t.slice(0, -1))
    }
  }

  const addPhotos = useCallback((files: FileList | null) => {
    if (!files) return
    const allowed = ['image/jpeg', 'image/png', 'image/webp']
    const valid = Array.from(files).filter(f => allowed.includes(f.type) && f.size <= 5 * 1024 * 1024)
    setPhotos(prev => {
      const next = [...prev, ...valid].slice(0, 5)
      setPhotoPreviews(next.map(f => URL.createObjectURL(f)))
      return next
    })
  }, [])

  const removePhoto = (i: number) => {
    setPhotos(prev => { const n = prev.filter((_, idx) => idx !== i); setPhotoPreviews(n.map(f => URL.createObjectURL(f))); return n })
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setError(null)
    setLoading(true)
    try {
      const fd = new FormData()
      fd.append('name', form.name)
      fd.append('description', form.description)
      fd.append('lat', form.lat)
      fd.append('lng', form.lng)
      if (form.altitude) fd.append('altitude', form.altitude)
      fd.append('difficulty', form.difficulty)
      fd.append('tags', JSON.stringify(tags))
      photos.forEach(f => fd.append('images', f))

      const res = await fetch('/api/spots', { method: 'POST', body: fd })
      const data = await res.json()
      if (!res.ok) {
        setError(data.error?.formErrors?.[0] ?? data.error ?? 'Erro ao submeter spot')
        return
      }
      router.push('/spots?submitted=true')
    } catch {
      setError('Erro de ligação. Tenta de novo.')
    } finally {
      setLoading(false)
    }
  }

  return (
    <motion.form
      className="spot-form"
      onSubmit={handleSubmit}
      initial={{ opacity: 0, y: 16 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.3 }}
    >
      {error && <div className="auth-error" role="alert">{error}</div>}

      {/* Informação básica */}
      <div>
        <p className="spot-form-section-title">Informação básica</p>

        <div className="form-group">
          <label className="form-label" htmlFor="name">Nome do spot *</label>
          <input
            id="name" name="name" className="form-input"
            value={form.name} onChange={handleChange}
            required minLength={3} maxLength={120}
            placeholder="Ex: Praia de Mira — zona norte"
          />
        </div>

        <div className="form-group" style={{ marginTop: 'var(--ov-space-4)' }}>
          <label className="form-label" htmlFor="description">Descrição *</label>
          <textarea
            id="description" name="description" className="form-input"
            value={form.description} onChange={handleChange}
            required minLength={20} maxLength={2000} rows={5}
            placeholder="Descreve o local, o que o torna especial, o que devem saber antes de voar, acessos, estacionamento…"
            style={{ resize: 'vertical' }}
          />
        </div>
      </div>

      {/* Localização */}
      <div>
        <p className="spot-form-section-title">Localização</p>

        <LocationPicker
          lat={form.lat}
          lng={form.lng}
          onPick={(lat, lng) => setForm((f) => ({
            ...f,
            lat: lat.toFixed(6),
            lng: lng.toFixed(6),
          }))}
        />

        <div className="spot-form-grid-2">
          <div className="form-group">
            <label className="form-label" htmlFor="lat">Latitude *</label>
            <input
              id="lat" name="lat" type="number" step="any" className="form-input"
              value={form.lat} onChange={handleChange} required
              placeholder="38.7223"
            />
          </div>
          <div className="form-group">
            <label className="form-label" htmlFor="lng">Longitude *</label>
            <input
              id="lng" name="lng" type="number" step="any" className="form-input"
              value={form.lng} onChange={handleChange} required
              placeholder="-9.1393"
            />
          </div>
        </div>
        <p className="coords-hint">
          Dica: abre o local no{' '}
          <a href="https://maps.google.com" target="_blank" rel="noopener noreferrer">Google Maps</a>,
          clica com o botão direito e copia as coordenadas.
        </p>

        <div className="form-group" style={{ marginTop: 'var(--ov-space-4)', maxWidth: 220 }}>
          <label className="form-label" htmlFor="altitude">Altitude máxima recomendada (m)</label>
          <input
            id="altitude" name="altitude" type="number" min="0" max="300" className="form-input"
            value={form.altitude} onChange={handleChange}
            placeholder="Ex: 120"
          />
        </div>
      </div>

      {/* Dificuldade */}
      <div>
        <p className="spot-form-section-title">Dificuldade</p>
        <div className="diff-cards">
          {DIFFICULTIES.map(({ value, label, desc }) => (
            <label key={value} className="diff-card">
              <input
                type="radio" name="difficulty" value={value}
                checked={form.difficulty === value}
                onChange={() => setForm((f) => ({ ...f, difficulty: value }))}
              />
              <span className="diff-card-label">
                <span className="diff-card-name">{label}</span>
                <span className="diff-card-desc">{desc}</span>
              </span>
            </label>
          ))}
        </div>
      </div>

      {/* Tags */}
      <div>
        <p className="spot-form-section-title">Tags</p>
        <label className="form-label" htmlFor="tag-input" style={{ marginBottom: 'var(--ov-space-2)', display: 'block' }}>
          Categorias do spot (máx. 8)
        </label>
        <div className="tags-input-wrap" onClick={() => tagInputRef.current?.focus()}>
          {tags.map((tag) => (
            <span key={tag} className="tag-pill">
              {tag}
              <button
                type="button" className="tag-pill-remove"
                onClick={(e) => { e.stopPropagation(); removeTag(tag) }}
                aria-label={`Remover tag ${tag}`}
              >
                ×
              </button>
            </span>
          ))}
          <input
            ref={tagInputRef} id="tag-input" className="tags-text-input"
            value={tagInput}
            onChange={(e) => setTagInput(e.target.value)}
            onKeyDown={handleTagKey}
            onBlur={() => tagInput.trim() && addTag(tagInput)}
            placeholder={tags.length === 0 ? 'praia, montanha, pôr-do-sol… (Enter para adicionar)' : ''}
            disabled={tags.length >= 8}
          />
        </div>
        {SUGGESTED_TAGS.filter((t) => !tags.includes(t)).length > 0 && (
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 'var(--ov-space-2)', marginTop: 'var(--ov-space-2)' }}>
            {SUGGESTED_TAGS.filter((t) => !tags.includes(t)).map((t) => (
              <button
                key={t} type="button"
                onClick={() => addTag(t)}
                style={{
                  padding: '2px 10px',
                  border: '1px solid var(--ov-line)',
                  borderRadius: '999px',
                  background: 'var(--ov-cloud)',
                  fontFamily: 'var(--ov-font-sans)',
                  fontSize: 12,
                  color: 'var(--ov-steel)',
                  cursor: 'pointer',
                }}
              >
                + {t}
              </button>
            ))}
          </div>
        )}
      </div>

      {/* Fotografias */}
      <div>
        <p className="spot-form-section-title">Fotografias</p>
        <input
          ref={photoInputRef}
          type="file"
          accept="image/jpeg,image/png,image/webp"
          multiple
          style={{ display: 'none' }}
          onChange={e => addPhotos(e.target.files)}
        />

        {/* Preview grid */}
        {photoPreviews.length > 0 && (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(100px, 1fr))', gap: 8, marginBottom: 10 }}>
            {photoPreviews.map((src, i) => (
              <div key={src} style={{ position: 'relative', borderRadius: 8, overflow: 'hidden', aspectRatio: '1', background: '#f0f0f0' }}>
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img src={src} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                {i === 0 && (
                  <span style={{ position: 'absolute', bottom: 4, left: 4, background: '#0096FF', color: '#fff', fontSize: 9, fontWeight: 700, padding: '2px 5px', borderRadius: 4, fontFamily: 'var(--ov-font-sans)' }}>CAPA</span>
                )}
                <button
                  type="button"
                  onClick={() => removePhoto(i)}
                  style={{ position: 'absolute', top: 3, right: 3, width: 20, height: 20, borderRadius: '50%', background: 'rgba(0,0,0,0.6)', color: '#fff', border: 'none', cursor: 'pointer', fontSize: 12, display: 'flex', alignItems: 'center', justifyContent: 'center', lineHeight: 1 }}
                  aria-label="Remover foto"
                >×</button>
              </div>
            ))}
          </div>
        )}

        {photos.length < 5 && (
          <button
            type="button"
            onClick={() => photoInputRef.current?.click()}
            style={{
              width: '100%', padding: '14px', border: '2px dashed var(--ov-line)', borderRadius: 10,
              background: 'var(--ov-cloud)', cursor: 'pointer', fontFamily: 'var(--ov-font-sans)',
              fontSize: 13, color: 'var(--ov-steel)', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
            }}
          >
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
            {photos.length === 0 ? 'Adicionar fotografias (máx. 5 · 5MB cada)' : `Adicionar mais (${photos.length}/5)`}
          </button>
        )}
      </div>

      <Button type="submit" loading={loading} style={{ width: '100%', justifyContent: 'center' }}>
        Submeter Spot para Moderação
      </Button>

      <p className="spot-form-note">
        O spot será analisado pela nossa equipa antes de aparecer na plataforma.
        Normalmente revisto em 24–48 horas.
      </p>
    </motion.form>
  )
}
