'use client';

import { motion, useReducedMotion } from 'framer-motion';
import { useId, useRef, type KeyboardEvent, type ReactNode } from 'react';

import { cn } from '@/lib/utils';

/** Underline tabs with a sliding 2px primary indicator (tablist semantics, arrow-key navigation). */
export function UnderlineTabs<T extends string>({
  value,
  tabs,
  onChange,
  label,
  className,
}: {
  value: T;
  tabs: ReadonlyArray<{ value: T; label: ReactNode; count?: number }>;
  onChange: (value: T) => void;
  label: string;
  className?: string;
}) {
  const reduce = useReducedMotion();
  const id = useId();
  const refs = useRef<Array<HTMLButtonElement | null>>([]);
  const onKeyDown = (event: KeyboardEvent<HTMLButtonElement>, index: number) => {
    const delta = event.key === 'ArrowRight' ? 1 : event.key === 'ArrowLeft' ? -1 : 0;
    if (delta === 0) return;
    event.preventDefault();
    const next = (index + delta + tabs.length) % tabs.length;
    const tab = tabs[next];
    if (tab === undefined) return;
    onChange(tab.value);
    refs.current[next]?.focus();
  };
  return (
    <div role="tablist" aria-label={label} className={cn('flex gap-1 overflow-x-auto border-b border-border', className)}>
      {tabs.map((tab, index) => {
        const selected = tab.value === value;
        return (
          <button
            key={tab.value}
            ref={(node) => {
              refs.current[index] = node;
            }}
            type="button"
            role="tab"
            aria-selected={selected}
            tabIndex={selected ? 0 : -1}
            onClick={() => onChange(tab.value)}
            onKeyDown={(event) => onKeyDown(event, index)}
            className={cn(
              'relative inline-flex h-11 shrink-0 items-center gap-2 px-3 text-small font-semibold transition-colors',
              selected ? 'text-foreground' : 'text-muted-foreground hover:text-foreground',
            )}
          >
            {tab.label}
            {tab.count === undefined || tab.count === 0 ? null : (
              <span className={cn('grid h-5 min-w-5 place-items-center rounded-pill px-1.5 text-[11px] font-bold', selected ? 'bg-primary text-primary-foreground' : 'bg-surface-muted text-muted-foreground')}>
                {tab.count}
              </span>
            )}
            {selected ? (
              <motion.span
                layoutId={`${id}-underline`}
                className="absolute inset-x-2 -bottom-px h-0.5 rounded-pill bg-primary"
                transition={reduce ? { duration: 0 } : { type: 'spring', stiffness: 500, damping: 40 }}
                aria-hidden="true"
              />
            ) : null}
          </button>
        );
      })}
    </div>
  );
}
