import { AnimatePresence, m } from 'framer-motion'
import { memo, type ReactNode } from 'react'
import './PageTabs.scss'

export type PageTabItem<TValue extends string> = {
  alert?: boolean
  label: ReactNode
  value: TValue
}

type PageTabsProps<TValue extends string> = {
  activeValue: TValue
  items: Array<PageTabItem<TValue>>
  onChange?: (value: TValue) => void
}

const tabMotion = {
  initial: {
    opacity: 0,
    x: -22,
    scale: 0.92,
  },
  animate: {
    opacity: 1,
    x: 0,
    scale: 1,
  },
  exit: {
    opacity: 0,
    x: -22,
    scale: 0.92,
  },
}

const tabTransition = {
  duration: 0.28,
  ease: [0.34, 1.42, 0.64, 1],
} as const

function PageTabsComponent<TValue extends string>({
  activeValue,
  items,
  onChange,
}: PageTabsProps<TValue>) {
  return (
    <div className="page-tabs">
      <AnimatePresence initial={false}>
        {items.map((item) => {
          const isActive = item.value === activeValue

          return (
            <m.button
              className={isActive ? 'page-tabs__item is-active' : 'page-tabs__item'}
              key={item.value}
              type="button"
              layout
              variants={tabMotion}
              initial="initial"
              animate="animate"
              exit="exit"
              transition={tabTransition}
              onClick={() => onChange?.(item.value)}
            >
              <span className="page-tabs__label">{item.label}</span>

              {item.alert && <span className="page-tabs__alert" />}
            </m.button>
          )
        })}
      </AnimatePresence>
    </div>
  )
}

export const PageTabs = memo(PageTabsComponent) as typeof PageTabsComponent
