import { type ComponentPropsWithoutRef, useEffect, useRef } from 'react';
import { Tabs as RTabs } from 'radix-ui';
import { cx } from '../utils';

export const Tabs = RTabs.Root;

export const TabsList = ({
  items,
  variant = 'primary',
  className,
  ...props
}: {
  items: Array<{ value: string; label: string }>;
  /** Visual style. `'primary'` (default) is the segmented pill track; `'secondary'` is the underline style. */
  variant?: 'primary' | 'secondary';
} & Omit<ComponentPropsWithoutRef<typeof RTabs.List>, 'children'>) => {
  const listRef = useRef<HTMLDivElement>(null);
  const thumbRef = useRef<HTMLSpanElement>(null);
  const initialized = useRef(false);

  useEffect(() => {
    const list = listRef.current;
    const thumb = thumbRef.current;
    if (!list || !thumb) return;

    const update = () => {
      const active = list.querySelector<HTMLElement>('[role="tab"][data-state="active"]');
      if (!active) return;

      if (!initialized.current) {
        thumb.style.transition = 'none';
      }
      thumb.style.transform = `translateX(${active.offsetLeft}px)`;
      thumb.style.width = `${active.offsetWidth}px`;
      if (!initialized.current) {
        thumb.getBoundingClientRect();
        thumb.style.transition = '';
        initialized.current = true;
      }
    };

    update();

    const attrObserver = new MutationObserver(update);
    list.querySelectorAll('[role="tab"]').forEach((tab) =>
      attrObserver.observe(tab, { attributes: true, attributeFilter: ['data-state'] }),
    );

    const resizeObserver = new ResizeObserver(update);
    resizeObserver.observe(list);

    return () => {
      attrObserver.disconnect();
      resizeObserver.disconnect();
    };
  }, [variant, items]);

  return (
    <RTabs.List ref={listRef} className={cx('mta-tabs', `mta-tabs--${variant}`, className)} {...props}>
      <span ref={thumbRef} className="mta-tabs__thumb" aria-hidden />
      {items.map((it) => (
        <RTabs.Trigger
          key={it.value}
          value={it.value}
          className="mta-tabs__trigger"
        >
          {it.label}
        </RTabs.Trigger>
      ))}
    </RTabs.List>
  );
};

export const TabsContent = RTabs.Content;
