import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { TABS_INLINE_STYLES } from './tabsInlineStyles.js';

export const TAB_IDS = {
  personal: 'personal',
  laboral: 'laboral',
  documentos: 'documentos',
};

/**
 * Pestañas por defecto del flujo alta/edición persona (misma lista que `AltaEdicionPersonas`).
 * @param {'create'|'edit'} [mode]
 * @param {function} [t]
 */
export function buildTabItems({ mode = 'create', t } = {}) {
  const translate =
    typeof t === 'function'
      ? t
      : (key, opts) => opts?.defaultValue ?? key;

  const items = [
    {
      id: TAB_IDS.personal,
      label: translate('persona.alta.tabPersonal', { defaultValue: 'Información personal' }),
    },
    {
      id: TAB_IDS.laboral,
      label: translate('persona.alta.tabLaboral', { defaultValue: 'Datos laborales' }),
    },
  ];

  if (mode === 'edit') {
    items.push({
      id: TAB_IDS.documentos,
      label: translate('persona.alta.tabDocumentos', { defaultValue: 'Documentos' }),
    });
  }

  return items;
}

/** Índice de pestaña acotado (0…n-1). */
export function clampTabIndex(raw, itemCount) {
  const max = Math.max(0, Number(itemCount) - 1);
  const n = Number(raw);
  if (!Number.isFinite(n)) return 0;
  return Math.min(Math.max(0, Math.floor(n)), max);
}

/**
 * Barra de pestañas Anima (misma UX que `AltaEdicionPersonas`), para el host.
 *
 * @param {Array<{ id: string, label: string, disabled?: boolean }>} [items]
 * @param {'create'|'edit'} [mode] — Si `items` se omite, genera pestañas del flujo persona.
 * @param {number} [activeIndex]
 * @param {number} [defaultActiveIndex]
 * @param {function} [onChange] — `(index, item) => void`
 * @param {string} [navAriaLabel]
 * @param {React.ReactNode} [headerBelowNav]
 */
export const Tabs = ({
  items: itemsProp,
  mode = 'create',
  activeIndex: activeIndexProp,
  defaultActiveIndex = 0,
  onChange,
  navAriaLabel,
  headerBelowNav,
  className = '',
  style,
  ...props
}) => {
  const { t, i18n } = useTranslation();
  const items =
    Array.isArray(itemsProp) && itemsProp.length > 0
      ? itemsProp
      : buildTabItems({ mode, t });

  const isControlled = activeIndexProp !== undefined && activeIndexProp !== null;
  const [internalIndex, setInternalIndex] = useState(() =>
    clampTabIndex(defaultActiveIndex, items.length),
  );

  const activeIndex = isControlled
    ? clampTabIndex(activeIndexProp, items.length)
    : internalIndex;

  const resolvedNavAriaLabel =
    navAriaLabel ?? t('persona.alta.tabsNavAriaLabel', { defaultValue: 'Secciones' });

  const handleSelect = (index) => {
    const item = items[index];
    if (item?.disabled) return;
    if (!isControlled) {
      setInternalIndex(index);
    }
    onChange?.(index, item);
  };

  return (
    <div className={`anima-tabs ${className}`.trim()} style={style} {...props}>
      <style>{TABS_INLINE_STYLES}</style>
      <div className="anima-tabs__shell">
        <div className="anima-tabs__wrap">
          <nav
            className="anima-tabs__nav"
            aria-label={resolvedNavAriaLabel}
            key={i18n.language}
          >
            {items.map((item, index) => {
              const isActive = activeIndex === index;
              return (
                <button
                  key={item.id ?? index}
                  type="button"
                  disabled={Boolean(item.disabled)}
                  onClick={() => handleSelect(index)}
                  className={
                    isActive
                      ? 'anima-tabs__tab anima-tabs__tab--active'
                      : 'anima-tabs__tab'
                  }
                  aria-current={isActive ? 'page' : undefined}
                >
                  {item.label}
                </button>
              );
            })}
          </nav>
        </div>
        {headerBelowNav != null ? headerBelowNav : null}
      </div>
    </div>
  );
};

export default Tabs;
