'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 SpotEditFormProps {
  spotId: string
  initialName: string
  initialDescription: string
  initialLat: number
  initialLng: number
  initialAltitude: number | null
  initialDifficulty: 'BEGINNER' | 'INTERMEDIATE' | 'ADVANCED'
  initialTags: string[]
  initialImages: string[]
}

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 SpotEditForm({
  spotId,
  initialName,
  initialDescription,
  initialLat,
  initialLng,
  initialAltitude,
  initialDifficulty,
  initialTags,
  initialImages,
}: SpotEditFormProps) {
  const router = useRouter()
  const tagInputRef = useRef<HTMLInputElement>(null)
  const photoInputRef = useRef<HTMLInputElement>(null)

  const [form, setForm] = useState({
    name: initialName,
    description: initialDescription,
    lat: String(initialLat),
    lng: String(initialLng),
    altitude: initialAltitude != null ? String(initialAltitude) : '',
    difficulty: initialDifficulty,
  })
  const [tags, setTags] = useState<string[]>(initialTags)
  const [tagInput, setTagInput] = useState('')
  const [keepImages, setKeepImages] = useState<string[]>(initialImages)
  const [newPhotos, setNewPhotos] = useState<File[]>([])
  const [newPreviews, setNewPreviews] = useState<string[]>([])
  const [error, setError] = useState<string | null>(null)
  const [loading, setLoading] = useState(false)

  const totalImages = keepImages.length + newPhotos.length

  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)
    setNewPhotos(prev => {
      const next = [...prev, ...valid].slice(0, 5 - keepImages.length)
      setNewPreviews(next.map(f => URL.createObjectURL(f)))
      return next
    })
  }, [keepImages.length])

  const removeKeepImage = (url: string) => setKeepImages(prev => prev.filter(u => u !== url))
  const removeNewPhoto = (i: number) => {
    setNewPhotos(prev => { const n = prev.filter((_, idx) => idx !== i); setNewPreviews(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))
      fd.append('keepImages', JSON.stringify(keepImages))
      newPhotos.forEach(f => fd.append('images', f))

      const res = await fetch(`/api/spots/${spotId}`, { method: 'PATCH', body: fd })
      const data = await res.json()
      if (!res.ok) {
        setError(data.error?.formErrors?.[0] ?? data.error ?? 'Erro ao guardar spot')
        return
      }
      router.push(`/spots/${spotId}`)
      router.refresh()
    } 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>}

      <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} />
        </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} style={{ resize: 'vertical' }} />
        </div>
      </div>

      <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 />
          </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 />
          </div>
        </div>
        <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>

      <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>

      <div>
        <p className="spot-form-section-title">Tags</p>
        <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… (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>

      <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)} />

        {(keepImages.length > 0 || newPreviews.length > 0) && (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(100px, 1fr))', gap: 8, marginBottom: 10 }}>
            {keepImages.map((url, i) => (
              <div key={url} style={{ position: 'relative', borderRadius: 8, overflow: 'hidden', aspectRatio: '1', background: '#f0f0f0' }}>
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img src={url} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                {i === 0 && keepImages.length + newPreviews.length > 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={() => removeKeepImage(url)}
                  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' }}
                  aria-label="Remover foto">×</button>
              </div>
            ))}
            {newPreviews.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' }} />
                {keepImages.length === 0 && 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>
                )}
                {!(keepImages.length === 0 && i === 0) && (
                  <span style={{ position: 'absolute', bottom: 4, left: 4, background: '#00B894', color: '#fff', fontSize: 9, fontWeight: 700, padding: '2px 5px', borderRadius: 4, fontFamily: 'var(--ov-font-sans)' }}>NOVA</span>
                )}
                <button type="button" onClick={() => removeNewPhoto(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' }}
                  aria-label="Remover foto">×</button>
              </div>
            ))}
          </div>
        )}

        {totalImages < 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>
            {totalImages === 0 ? 'Adicionar fotografias (máx. 5 · 5MB cada)' : `Adicionar mais (${totalImages}/5)`}
          </button>
        )}
      </div>

      <Button type="submit" loading={loading} style={{ width: '100%', justifyContent: 'center' }}>
        Guardar Alterações
      </Button>
    </motion.form>
  )
}
