'use client'
import { useEffect, useRef, useState } from 'react'
import { toast } from '@/components/ui/toaster'
import { cn } from '@/lib/utils'
import { Upload, X, ZoomIn, ChevronLeft, ChevronRight, Share2, Download, Copy, Check } from 'lucide-react'

interface Foto { id: string; url: string; tipo: 'antes' | 'despues'; created_at: string }

interface Props {
  citaId: string
  servicio: string
  fechaCita: string
  readOnly?: boolean
}

// ── Redes sociales ──────────────────────────────────────────
const REDES = [
  {
    id: 'whatsapp',
    label: 'WhatsApp',
    color: '#25D366',
    icon: (
      <svg viewBox="0 0 24 24" className="h-5 w-5" fill="currentColor">
        <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/>
      </svg>
    ),
    getUrl: (url: string, texto: string) =>
      `https://wa.me/?text=${encodeURIComponent(`${texto}\n${url}`)}`,
  },
  {
    id: 'facebook',
    label: 'Facebook',
    color: '#1877F2',
    icon: (
      <svg viewBox="0 0 24 24" className="h-5 w-5" fill="currentColor">
        <path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/>
      </svg>
    ),
    getUrl: (url: string) =>
      `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(url)}`,
  },
  {
    id: 'twitter',
    label: 'X / Twitter',
    color: '#000000',
    icon: (
      <svg viewBox="0 0 24 24" className="h-5 w-5" fill="currentColor">
        <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-4.714-6.231-5.401 6.231H2.744l7.737-8.835L1.254 2.25H8.08l4.259 5.632 5.905-5.632zm-1.161 17.52h1.833L7.084 4.126H5.117z"/>
      </svg>
    ),
    getUrl: (url: string, texto: string) =>
      `https://twitter.com/intent/tweet?text=${encodeURIComponent(texto)}&url=${encodeURIComponent(url)}`,
  },
  {
    id: 'instagram',
    label: 'Instagram',
    color: '#E1306C',
    icon: (
      <svg viewBox="0 0 24 24" className="h-5 w-5" fill="currentColor">
        <path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zM12 0C8.741 0 8.333.014 7.053.072 2.695.272.273 2.69.073 7.052.014 8.333 0 8.741 0 12c0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98C8.333 23.986 8.741 24 12 24c3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98C15.668.014 15.259 0 12 0zm0 5.838a6.162 6.162 0 100 12.324 6.162 6.162 0 000-12.324zM12 16a4 4 0 110-8 4 4 0 010 8zm6.406-11.845a1.44 1.44 0 100 2.881 1.44 1.44 0 000-2.881z"/>
      </svg>
    ),
    getUrl: (url: string) => url, // Solo copia — Instagram no permite share directo por URL
    solocopiar: true,
  },
]

export function FotosCita({ citaId, servicio, fechaCita, readOnly = false }: Props) {
  const [fotos, setFotos] = useState<Foto[]>([])
  const [cargando, setCargando] = useState(true)
  const [subiendo, setSubiendo] = useState<'antes' | 'despues' | null>(null)
  const [lightbox, setLightbox] = useState<{ fotos: Foto[]; index: number } | null>(null)
  const inputAntesRef = useRef<HTMLInputElement>(null)
  const inputDespuesRef = useRef<HTMLInputElement>(null)

  const cargar = async () => {
    setCargando(true)
    const res = await fetch(`/api/fotos?cita_id=${citaId}`)
    const { fotos } = await res.json()
    setFotos(fotos ?? [])
    setCargando(false)
  }

  useEffect(() => { cargar() }, [citaId])

  const fotosAntes   = fotos.filter(f => f.tipo === 'antes')
  const fotosDespues = fotos.filter(f => f.tipo === 'despues')

  const handleSubir = async (e: React.ChangeEvent<HTMLInputElement>, tipo: 'antes' | 'despues') => {
    const archivos = Array.from(e.target.files ?? [])
    if (!archivos.length) return
    const actuales = tipo === 'antes' ? fotosAntes.length : fotosDespues.length
    const disponibles = 3 - actuales
    const aSubir = archivos.slice(0, disponibles)
    if (archivos.length > disponibles) toast(`Solo puedes subir ${disponibles} foto(s) más`, 'info')

    setSubiendo(tipo)
    let subidas = 0
    for (const archivo of aSubir) {
      const fd = new FormData()
      fd.append('file', archivo)
      fd.append('cita_id', citaId)
      fd.append('tipo', tipo)
      const res = await fetch('/api/fotos', { method: 'POST', body: fd })
      const data = await res.json()
      if (res.ok) subidas++
      else toast(data.error ?? 'Error al subir foto', 'error')
    }
    if (subidas > 0) { toast(`${subidas} foto(s) subida(s)`, 'success'); await cargar() }
    setSubiendo(null)
    if (tipo === 'antes' && inputAntesRef.current) inputAntesRef.current.value = ''
    if (tipo === 'despues' && inputDespuesRef.current) inputDespuesRef.current.value = ''
  }

  const handleEliminar = async (id: string) => {
    if (!confirm('¿Eliminar esta foto?')) return
    const res = await fetch(`/api/fotos?id=${id}`, { method: 'DELETE' })
    if (res.ok) { toast('Foto eliminada', 'info'); await cargar() }
    else toast('Error al eliminar', 'error')
  }

  const abrirLightbox = (tipo: 'antes' | 'despues', index: number) => {
    const lista = tipo === 'antes' ? fotosAntes : fotosDespues
    setLightbox({ fotos: lista, index })
  }

  if (cargando) return (
    <div className="flex justify-center py-8">
      <div className="w-5 h-5 border border-[#C9A84C] border-t-transparent rounded-full animate-spin" />
    </div>
  )

  const tieneFotos = fotos.length > 0

  return (
    <div className="mt-4">
      {!tieneFotos && !readOnly ? (
        <p className="text-[#444] text-xs tracking-widest uppercase mb-4">Añade fotos de tu transformación</p>
      ) : tieneFotos ? (
        <p className="text-[#C9A84C] text-[10px] tracking-[0.3em] uppercase mb-4">Transformación — {servicio}</p>
      ) : null}

      {(tieneFotos || !readOnly) && (
        <div className="grid grid-cols-2 gap-4">
          <PanelFotos tipo="antes"   fotos={fotosAntes}   readOnly={readOnly} subiendo={subiendo === 'antes'}   inputRef={inputAntesRef}   onSubir={e => handleSubir(e, 'antes')}   onEliminar={handleEliminar} onZoom={i => abrirLightbox('antes', i)} />
          <PanelFotos tipo="despues" fotos={fotosDespues} readOnly={readOnly} subiendo={subiendo === 'despues'} inputRef={inputDespuesRef} onSubir={e => handleSubir(e, 'despues')} onEliminar={handleEliminar} onZoom={i => abrirLightbox('despues', i)} />
        </div>
      )}

      {lightbox && (
        <Lightbox
          fotos={lightbox.fotos}
          index={lightbox.index}
          servicio={servicio}
          onClose={() => setLightbox(null)}
          onChange={i => setLightbox(prev => prev ? { ...prev, index: i } : null)}
        />
      )}
    </div>
  )
}

/* ── Panel ── */
function PanelFotos({ tipo, fotos, readOnly, subiendo, inputRef, onSubir, onEliminar, onZoom }: {
  tipo: 'antes' | 'despues'
  fotos: Foto[]
  readOnly: boolean
  subiendo: boolean
  inputRef: React.RefObject<HTMLInputElement | null>
  onSubir: (e: React.ChangeEvent<HTMLInputElement>) => void
  onEliminar: (id: string) => void
  onZoom: (index: number) => void
}) {
  const esAntes = tipo === 'antes'
  const label   = esAntes ? 'Antes' : 'Después'
  const color   = esAntes ? 'text-[#888]' : 'text-[#C9A84C]'
  const border  = esAntes ? 'border-[#222]' : 'border-[#C9A84C]/30'

  return (
    <div>
      <div className={`flex items-center justify-between mb-2 pb-2 border-b ${border}`}>
        <span className={`text-[10px] tracking-[0.3em] uppercase font-medium ${color}`}>{label}</span>
        <span className="text-[10px] text-[#333]">{fotos.length}/3</span>
      </div>
      <div className="grid grid-cols-3 gap-1.5">
        {fotos.map((f, i) => (
          <div key={f.id} className="relative aspect-square group">
            <img src={f.url} alt={`${label} ${i + 1}`} className="w-full h-full object-cover cursor-pointer" onClick={() => onZoom(i)} />
            <div className="absolute inset-0 bg-black/0 group-hover:bg-black/50 transition-all flex items-center justify-center gap-1.5 opacity-0 group-hover:opacity-100">
              <button onClick={() => onZoom(i)} className="bg-black/70 text-white p-1.5 hover:bg-[#C9A84C] hover:text-black transition-colors">
                <ZoomIn className="h-3 w-3" />
              </button>
              {!readOnly && (
                <button onClick={() => onEliminar(f.id)} className="bg-red-900/80 text-red-300 p-1.5 hover:bg-red-700 transition-colors">
                  <X className="h-3 w-3" />
                </button>
              )}
            </div>
          </div>
        ))}
        {!readOnly && Array.from({ length: 3 - fotos.length }).map((_, i) => (
          <button key={`empty-${i}`} onClick={() => inputRef.current?.click()} disabled={subiendo}
            className={cn(
              'aspect-square border border-dashed flex items-center justify-center transition-all',
              esAntes ? 'border-[#222] hover:border-[#444] text-[#333] hover:text-[#555]'
                      : 'border-[#C9A84C]/20 hover:border-[#C9A84C]/50 text-[#C9A84C]/30 hover:text-[#C9A84C]/60',
              subiendo && 'opacity-40 cursor-not-allowed'
            )}>
            {subiendo && i === 0
              ? <div className="w-3.5 h-3.5 border border-current border-t-transparent rounded-full animate-spin" />
              : <Upload className="h-3.5 w-3.5" />}
          </button>
        ))}
        {readOnly && fotos.length === 0 && (
          <div className="col-span-3 py-4 text-center text-[#333] text-xs">Sin fotos</div>
        )}
      </div>
      <input ref={inputRef} type="file" accept="image/*" multiple className="hidden" onChange={onSubir} />
    </div>
  )
}

/* ── Lightbox con compartir ── */
function Lightbox({ fotos, index, servicio, onClose, onChange }: {
  fotos: Foto[]
  index: number
  servicio: string
  onClose: () => void
  onChange: (i: number) => void
}) {
  const [mostrarShare, setMostrarShare] = useState(false)
  const [copiado, setCopiado] = useState(false)
  const foto = fotos[index]
  const textoCompartir = `✂️ Mi transformación en Barbería Lukakin — ${servicio}`

  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      if (e.key === 'Escape') { if (mostrarShare) setMostrarShare(false); else onClose() }
      if (e.key === 'ArrowRight' && index < fotos.length - 1) onChange(index + 1)
      if (e.key === 'ArrowLeft'  && index > 0) onChange(index - 1)
    }
    window.addEventListener('keydown', handler)
    return () => window.removeEventListener('keydown', handler)
  }, [index, fotos.length, mostrarShare])

  const copiarEnlace = async () => {
    await navigator.clipboard.writeText(foto.url)
    setCopiado(true)
    toast('Enlace copiado', 'success')
    setTimeout(() => setCopiado(false), 2000)
  }

  const descargar = async () => {
    const res = await fetch(foto.url)
    const blob = await res.blob()
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `lukakin-${foto.tipo}-${index + 1}.jpg`
    a.click()
    URL.revokeObjectURL(url)
  }

  const compartirNativo = async () => {
    if (navigator.share) {
      try {
        await navigator.share({ title: 'Barbería Lukakin', text: textoCompartir, url: foto.url })
      } catch {}
    } else {
      setMostrarShare(true)
    }
  }

  const abrirRed = (red: typeof REDES[0]) => {
    if (red.solocopiar) {
      copiarEnlace()
      toast('Copia el enlace y pégalo en Instagram', 'info')
      return
    }
    window.open(red.getUrl(foto.url, textoCompartir), '_blank', 'noopener,noreferrer')
  }

  return (
    <div className="fixed inset-0 z-50 bg-black/96 flex flex-col items-center justify-center" onClick={() => { if (mostrarShare) setMostrarShare(false); else onClose() }}>

      {/* Barra superior */}
      <div className="absolute top-0 left-0 right-0 flex items-center justify-between px-5 py-4" onClick={e => e.stopPropagation()}>
        <span className="text-[10px] text-[#444] tracking-[0.3em] uppercase">
          {foto.tipo === 'antes' ? 'Antes' : 'Después'} · {index + 1}/{fotos.length}
        </span>
        <div className="flex items-center gap-3">
          {/* Descargar */}
          <button onClick={descargar} title="Descargar"
            className="text-[#555] hover:text-[#C9A84C] transition-colors p-1.5 hover:bg-white/5">
            <Download className="h-4 w-4" />
          </button>

          {/* Compartir */}
          <button onClick={compartirNativo} title="Compartir"
            className="flex items-center gap-2 text-[10px] tracking-widest uppercase bg-[#C9A84C] hover:bg-[#E8C97A] text-black font-semibold px-3 py-1.5 transition-all">
            <Share2 className="h-3.5 w-3.5" />
            Compartir
          </button>

          {/* Cerrar */}
          <button onClick={onClose} className="text-[#555] hover:text-white transition-colors p-1.5">
            <X className="h-5 w-5" />
          </button>
        </div>
      </div>

      {/* Flecha izquierda */}
      {index > 0 && (
        <button className="absolute left-4 text-[#555] hover:text-[#C9A84C] transition-colors z-10"
          onClick={e => { e.stopPropagation(); onChange(index - 1) }}>
          <ChevronLeft className="h-8 w-8" />
        </button>
      )}

      {/* Imagen */}
      <img
        src={foto.url}
        alt="Foto ampliada"
        className="max-h-[80vh] max-w-[85vw] object-contain"
        onClick={e => e.stopPropagation()}
      />

      {/* Flecha derecha */}
      {index < fotos.length - 1 && (
        <button className="absolute right-4 text-[#555] hover:text-[#C9A84C] transition-colors z-10"
          onClick={e => { e.stopPropagation(); onChange(index + 1) }}>
          <ChevronRight className="h-8 w-8" />
        </button>
      )}

      {/* Panel de redes sociales */}
      {mostrarShare && (
        <div
          className="absolute bottom-0 left-0 right-0 bg-[#0a0a0a] border-t border-[#C9A84C]/20 px-6 py-6"
          onClick={e => e.stopPropagation()}
        >
          <p className="text-[10px] text-[#C9A84C] tracking-[0.35em] uppercase mb-5 text-center">
            Compartir transformación
          </p>

          <div className="grid grid-cols-4 gap-3 max-w-sm mx-auto mb-5">
            {REDES.map(red => (
              <button
                key={red.id}
                onClick={() => abrirRed(red)}
                className="flex flex-col items-center gap-2 group"
              >
                <div
                  className="w-12 h-12 flex items-center justify-center transition-all group-hover:scale-110"
                  style={{ backgroundColor: red.color + '20', color: red.color, border: `1px solid ${red.color}30` }}
                >
                  {red.icon}
                </div>
                <span className="text-[9px] text-[#444] tracking-wide group-hover:text-[#888] transition-colors">
                  {red.id === 'instagram' ? 'Copiar link' : red.label}
                </span>
              </button>
            ))}
          </div>

          {/* Copiar enlace directo */}
          <div className="flex items-center gap-2 bg-[#0d0d0d] border border-[#1a1a1a] px-3 py-2 max-w-sm mx-auto">
            <span className="text-[#444] text-xs truncate flex-1">{foto.url}</span>
            <button onClick={copiarEnlace}
              className="shrink-0 text-[#C9A84C] hover:text-[#E8C97A] transition-colors">
              {copiado ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}
            </button>
          </div>

          <button
            onClick={() => setMostrarShare(false)}
            className="block mx-auto mt-4 text-[10px] text-[#333] hover:text-[#555] tracking-widest uppercase transition-colors"
          >
            Cerrar
          </button>
        </div>
      )}
    </div>
  )
}
