"use client"

import { useCallback, useEffect, useRef, useState } from "react"

import { cn } from "@/lib/utils"

export type FollowUpSuggestion = {
  prompt: string
  title?: string
  label?: string
}

export function FollowUpSuggestions({
  suggestions,
  onSelect,
  className,
}: {
  suggestions: readonly FollowUpSuggestion[]
  onSelect?: (prompt: string) => void
  className?: string
}) {
  const scrollRef = useRef<HTMLDivElement>(null)
  const rtlRef = useRef<boolean | null>(null)
  const [fades, setFades] = useState({ left: false, right: false })

  const updateFades = useCallback(() => {
    const el = scrollRef.current
    if (!el) return
    const maxScroll = el.scrollWidth - el.clientWidth
    const fromStart = Math.abs(el.scrollLeft)
    const rtl = (rtlRef.current ??=
      getComputedStyle(el).direction === "rtl")
    const [left, right] = rtl
      ? [maxScroll - fromStart, fromStart]
      : [fromStart, maxScroll - fromStart]
    setFades((prev) => {
      const next = { left: left > 1, right: right > 1 }
      return prev.left === next.left && prev.right === next.right ? prev : next
    })
  }, [])

  useEffect(() => {
    updateFades()
    const el = scrollRef.current
    if (!el?.firstElementChild) return undefined
    const observer = new ResizeObserver(updateFades)
    observer.observe(el)
    observer.observe(el.firstElementChild)
    return () => observer.disconnect()
  }, [updateFades, suggestions])

  if (suggestions.length === 0) return null

  const maskImage = `linear-gradient(to right, ${
    fades.left ? "transparent, black 2rem" : "black"
  }, ${fades.right ? "black calc(100% - 2rem), transparent" : "black"})`

  return (
    <div
      ref={scrollRef}
      onScroll={updateFades}
      data-slot="follow-up-suggestions"
      className={cn(
        "-my-1 w-full overflow-x-auto py-1 [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",
        className
      )}
      style={{ maskImage, WebkitMaskImage: maskImage }}
    >
      <div className="mx-auto flex min-h-8 w-max items-center gap-2 px-0.5">
        {suggestions.map((suggestion, idx) => (
          <button
            key={idx}
            type="button"
            className="bg-background hover:bg-muted/80 rounded-full border px-3 py-1 text-sm whitespace-nowrap transition-colors ease-in"
            onClick={() => onSelect?.(suggestion.prompt)}
          >
            {suggestion.title ?? suggestion.prompt}
            {suggestion.label ? (
              <span className="text-muted-foreground ms-1">
                {suggestion.label}
              </span>
            ) : null}
          </button>
        ))}
      </div>
    </div>
  )
}