import { useRef, useState } from 'react'
import { ChevronLeft, ChevronRight, Image as ImageIcon, MousePointerClick } from 'lucide-react'
import { cn } from '@/lib/utils'
import { DynIcon } from '@/lib/blocks/icons'
import { RichText } from '@/lib/blocks/richText'
import type { FlipcardsData, CarouselData } from '@/lib/blocks/types'
import { BlockRenderProps, EmptyHint, SectionTitle } from './shared'

// ---------- Cartões de virada ----------

export function FlipcardsBlock({ data, theme }: BlockRenderProps<FlipcardsData>) {
  const [flipped, setFlipped] = useState<Set<number>>(new Set())

  const toggle = (i: number) => {
    setFlipped((prev) => {
      const next = new Set(prev)
      if (next.has(i)) next.delete(i)
      else next.add(i)
      return next
    })
  }

  return (
    <div>
      <SectionTitle title={data.title} />
      {data.items.length === 0 ? (
        <EmptyHint label="Adicione cartões no painel de propriedades" />
      ) : (
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {data.items.map((item, i) => {
            const isFlipped = flipped.has(i)
            return (
              <button
                key={i}
                type="button"
                onClick={() => toggle(i)}
                className="h-52 w-full [perspective:1200px] focus-visible:outline-none"
                aria-label={`Cartão ${i + 1}: ${item.front}. Clique para virar.`}
              >
                <div
                  className={cn(
                    'relative h-full w-full transition-transform duration-500 [transform-style:preserve-3d]',
                    isFlipped && '[transform:rotateY(180deg)]'
                  )}
                >
                  <div
                    className="absolute inset-0 flex flex-col items-center justify-center gap-3 rounded-xl p-5 text-white shadow-md [backface-visibility:hidden]"
                    style={{ background: theme.gradient }}
                  >
                    <DynIcon name={item.icon} className="h-9 w-9" aria-hidden />
                    <p className="text-center text-lg font-bold">{item.front || `Cartão ${i + 1}`}</p>
                    <span className="absolute bottom-3 flex items-center gap-1.5 text-xs font-medium text-white/80">
                      <MousePointerClick className="h-3.5 w-3.5" />
                      Clique para virar
                    </span>
                  </div>
                  <div
                    className="absolute inset-0 flex items-center justify-center overflow-y-auto rounded-xl border-2 bg-white p-5 shadow-md [backface-visibility:hidden] [transform:rotateY(180deg)]"
                    style={{ borderColor: theme.soft }}
                  >
                    <RichText
                      text={item.back || 'Verso do cartão'}
                      className="text-center text-sm leading-relaxed text-slate-600"
                    />
                  </div>
                </div>
              </button>
            )
          })}
        </div>
      )}
    </div>
  )
}

// ---------- Carrossel ----------

export function CarouselBlock({ data, mode }: BlockRenderProps<CarouselData>) {
  const trackRef = useRef<HTMLDivElement | null>(null)
  const [atStart, setAtStart] = useState(true)
  const [atEnd, setAtEnd] = useState(false)

  const updateEdges = () => {
    const el = trackRef.current
    if (!el) return
    setAtStart(el.scrollLeft <= 8)
    setAtEnd(el.scrollLeft + el.clientWidth >= el.scrollWidth - 8)
  }

  const scroll = (dir: -1 | 1) => {
    trackRef.current?.scrollBy({ left: dir * 340, behavior: 'smooth' })
  }

  if (data.items.length === 0) {
    return <EmptyHint label="Adicione slides no painel de propriedades" />
  }

  return (
    <div className="group/carousel relative">
      <div
        ref={trackRef}
        onScroll={updateEdges}
        className="no-scrollbar flex snap-x snap-mandatory gap-4 overflow-x-auto scroll-smooth pb-1"
      >
        {data.items.map((item, i) => (
          <div
            key={i}
            className="w-[280px] shrink-0 snap-start overflow-hidden rounded-xl border border-slate-200 bg-white shadow-sm sm:w-[320px]"
          >
            <CarouselImage src={item.imageUrl} alt={item.title} />
            <div className="p-4">
              <h4 className="mb-1 text-base font-semibold text-slate-900">{item.title || `Slide ${i + 1}`}</h4>
              <RichText text={item.description} className="text-sm leading-relaxed text-slate-600" />
            </div>
          </div>
        ))}
      </div>

      {mode === 'edit' && <div className="absolute inset-x-0 top-0 h-44" aria-hidden />}

      <button
        type="button"
        onClick={() => scroll(-1)}
        disabled={atStart}
        className={cn(
          'absolute top-[70px] -left-3 z-10 flex h-9 w-9 items-center justify-center rounded-full border border-slate-200 bg-white text-slate-600 shadow-md transition-opacity hover:bg-slate-50 disabled:pointer-events-none disabled:opacity-0',
          atStart && 'opacity-0'
        )}
        aria-label="Slide anterior"
      >
        <ChevronLeft className="h-5 w-5" />
      </button>
      <button
        type="button"
        onClick={() => scroll(1)}
        disabled={atEnd}
        className={cn(
          'absolute top-[70px] -right-3 z-10 flex h-9 w-9 items-center justify-center rounded-full border border-slate-200 bg-white text-slate-600 shadow-md transition-opacity hover:bg-slate-50 disabled:pointer-events-none disabled:opacity-0',
          atEnd && 'opacity-0'
        )}
        aria-label="Próximo slide"
      >
        <ChevronRight className="h-5 w-5" />
      </button>
    </div>
  )
}

function CarouselImage({ src, alt }: { src: string; alt: string }) {
  const [failed, setFailed] = useState(false)
  if (!src || failed) {
    return (
      <div className="flex h-44 w-full items-center justify-center bg-gradient-to-br from-slate-100 to-slate-200 text-slate-400">
        <ImageIcon className="h-8 w-8" />
      </div>
    )
  }
  return (
    <img
      src={src}
      alt={alt}
      className="h-44 w-full object-cover"
      onError={() => setFailed(true)}
      loading="lazy"
    />
  )
}
