import type { JSX } from 'preact';
import { cn } from './cn';
import { ScrollArea } from './ScrollArea';
import { AsukaIcon } from './AsukaIcon';

export type TabsItem = {
  id: string;
  label: string;
  icon?: JSX.Element | string;
  disabled?: boolean;
};

export interface TabsProps {
  items: TabsItem[];
  value: string;
  onChange: (id: string) => void;
  className?: string;
}

/**
 * Tabs (core)
 * - Lightweight underline tabs with horizontal custom scroll when headers overflow.
 */
export function Tabs({ items, value, onChange, className }: TabsProps) {
  return (
    <div className={cn('ask-tabs ask-w-full ask-border-b ask-border-borderSubtle', className)}>
      <ScrollArea
        axis="horizontal"
        className="ask-w-full"
        viewportClassName="ask-pb-1"
        contentClassName="ask-tabs__list ask-inline-flex ask-min-w-max ask-items-center ask-gap-6 ask-px-1"
      >
        {items.map((it) => {
          const active = it.id === value;
          return (
            <button
              key={it.id}
              type="button"
              title={it.label}
              disabled={it.disabled}
              className={cn(
                'ask-tabs__trigger ask-relative ask-shrink-0 ask-inline-flex ask-items-center ask-gap-2 ask-bg-transparent ask-px-0.5 ask-py-3 ask-text-[12px] ask-font-medium ask-transition-colors focus:ask-outline-none',
                active && 'is-active',
                it.disabled && 'is-disabled',
              )}
              onClick={() => onChange(it.id)}
              aria-current={active ? 'page' : undefined}
              aria-selected={active}
            >
              {it.icon ? (
                typeof it.icon === 'string' ? (
                  <AsukaIcon name={it.icon} size={14} className="ask-shrink-0" />
                ) : (
                  <span className="ask-leading-none">{it.icon}</span>
                )
              ) : null}
              <span className="ask-max-w-[180px] ask-truncate">{it.label}</span>
            </button>
          );
        })}
      </ScrollArea>
    </div>
  );
}
