import { useLayoutEffect, useMemo, useRef, useState } from "react"
import type { DealPreset } from "../../api/deal/getDeal"

const TABS: { key: DealPreset; label: string }[] = [
  { key: "hot", label: "Sıcak" },
  { key: "trending", label: "Trend" },
  { key: "new", label: "Yeni" },
]

type DealsPresetTabsProps = {
  currentPreset: DealPreset
  onSelect: (preset: DealPreset) => void
}

export default function DealsPresetTabs({ currentPreset, onSelect }: DealsPresetTabsProps) {
  const containerRef = useRef<HTMLDivElement | null>(null)
  const btnRefs = useRef<Record<string, HTMLButtonElement | null>>({})
  const [indicator, setIndicator] = useState({ left: 0, width: 0 })

  const activeIndex = useMemo(
    () => Math.max(0, TABS.findIndex((t) => t.key === currentPreset)),
    [currentPreset]
  )

  const updateIndicator = () => {
    const container = containerRef.current
    const activeKey = TABS[activeIndex]?.key
    const btn = activeKey ? btnRefs.current[activeKey] : null
    if (!container || !btn) return

    const cRect = container.getBoundingClientRect()
    const bRect = btn.getBoundingClientRect()

    // container içindeki left offset
    const left = bRect.left - cRect.left
    const width = bRect.width

    setIndicator({ left, width })
  }

  useLayoutEffect(() => {
    updateIndicator()
    // resize olunca da otursun
    const onResize = () => updateIndicator()
    window.addEventListener("resize", onResize)
    return () => window.removeEventListener("resize", onResize)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [activeIndex])

  return (
    <div
      ref={containerRef}
      className="relative inline-flex items-center rounded-full bg-surface-2 p-1 border border-white/10"
    >
      {/* sliding indicator (tam yazının oturduğu button genişliği kadar) */}
      <div
        className="absolute top-1 bottom-1 rounded-full bg-background/50 border border-white/10 shadow-sm transition-all duration-200"
        style={{ left: indicator.left, width: indicator.width }}
      />

      {TABS.map((tab) => {
        const isActive = tab.key === currentPreset
        return (
          <button
            key={tab.key}
            ref={(el) => {
              btnRefs.current[tab.key] = el
            }}
            type="button"
            onClick={() => onSelect(tab.key)}
            className={[
              "relative z-10",
              "px-4 py-2 text-m font-bold rounded-full",
              "transition-colorstext-primary",
              // turuncu ring iptal:
              "focus:outline-none",
              isActive ? "text-primary shadow " : "text-text-muted hover:text-text",
            ].join(" ")}
          >
            {tab.label}
          </button>
        )
      })}
    </div>
  )
}
