'use client';

import { useLayoutEffect, useMemo, useRef, useState } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { cn } from '@/lib/utils/cn';
import { OsDropdown } from './object-settings/primitives';

export type GeneralTabDef = { id: string; label: string };

/**
 * Folder-style `.os-tabs` with a More menu.
 * Tabs in `alwaysInMore` stay in that menu at every width (General keeps
 * Security and Automation there). Anything else still overflows into it
 * when the row runs out of room. With `noMore` every tab stays in the row
 * and the row scrolls sideways instead (General, like HubSpot: no More menu).
 */
export function GeneralOsTabs({
  label,
  tabs,
  active,
  onSelect,
  alwaysInMore = [],
  noMore = false,
}: {
  label: string;
  tabs: GeneralTabDef[];
  active: string;
  onSelect: (id: string) => void;
  alwaysInMore?: string[];
  noMore?: boolean;
}) {
  const navRef = useRef<HTMLElement>(null);
  const widths = useRef<Record<string, number>>({});
  const pinnedKey = alwaysInMore.join('|');
  const primary = useMemo(() => {
    const pinned = new Set(pinnedKey ? pinnedKey.split('|') : []);
    return tabs.filter((t) => !pinned.has(t.id));
  }, [tabs, pinnedKey]);
  const [fit, setFit] = useState(primary.length);

  useLayoutEffect(() => {
    const nav = navRef.current;
    const bar = nav?.parentElement;
    if (!nav || !bar || noMore) return;
    nav.querySelectorAll<HTMLElement>('[data-os-tab]').forEach((el) => {
      if (el.offsetWidth) widths.current[el.dataset.osTab!] = el.offsetWidth;
    });
    const measure = () => {
      const room = bar.clientWidth;
      const more = nav.querySelector<HTMLElement>('.os-tab-more')?.offsetWidth || 112;
      const moreAlways = pinnedKey.length > 0;
      let used = 0;
      let n = 0;
      for (const t of primary) {
        const w = widths.current[t.id] ?? 120;
        const last = n === primary.length - 1 && !moreAlways;
        if (used + w + (last ? 0 : more) > room) break;
        used += w;
        n++;
      }
      setFit(Math.max(primary.length ? 1 : 0, n));
    };
    measure();
    const ro = new ResizeObserver(measure);
    ro.observe(bar);
    return () => ro.disconnect();
  }, [primary, pinnedKey, noMore]);

  // `noMore` rows that scroll fade the edge that has more tabs past it (SQ-15),
  // and keep the active and the focused tab fully in view.
  const [edges, setEdges] = useState({ start: false, end: false });
  useLayoutEffect(() => {
    const nav = navRef.current;
    if (!nav || !noMore) return;
    const update = () => {
      const max = nav.scrollWidth - nav.clientWidth;
      const start = nav.scrollLeft > 1;
      const end = nav.scrollLeft < max - 1;
      setEdges((e) => (e.start === start && e.end === end ? e : { start, end }));
    };
    const onFocus = (e: FocusEvent) => {
      if (e.target instanceof HTMLElement) revealTab(nav, e.target);
    };
    update();
    nav.addEventListener('scroll', update, { passive: true });
    nav.addEventListener('focusin', onFocus);
    const ro = new ResizeObserver(update);
    ro.observe(nav);
    return () => {
      nav.removeEventListener('scroll', update);
      nav.removeEventListener('focusin', onFocus);
      ro.disconnect();
    };
  }, [noMore]);
  useLayoutEffect(() => {
    const nav = navRef.current;
    const el = nav?.querySelector<HTMLElement>(`[data-os-tab="${CSS.escape(active)}"]`);
    if (nav && el && noMore) revealTab(nav, el);
  }, [active, noMore]);

  let shown = (noMore ? tabs : primary.slice(0, fit)).map((t) => t.id);
  if (primary.some((t) => t.id === active) && !shown.includes(active)) {
    shown = [...shown.slice(0, Math.max(0, shown.length - 1)), active];
  }
  const hidden = tabs.filter((t) => !shown.includes(t.id));
  const moreActive = hidden.some((t) => t.id === active);

  return (
    <div className="os-tabbar os-tabbar--full crm-mb-4">
      <nav
        className={cn(
          'os-tabs',
          noMore && 'os-tabs--scroll',
          noMore && edges.start && 'os-tabs--more-start',
          noMore && edges.end && 'os-tabs--more-end',
        )}
        aria-label={label}
        ref={navRef}
      >
        {tabs.map((t) => (
          <button
            key={t.id}
            type="button"
            data-os-tab={t.id}
            className={cn('os-tab', t.id === active && 'is-active')}
            aria-current={t.id === active ? 'page' : undefined}
            hidden={!shown.includes(t.id)}
            onClick={() => onSelect(t.id)}
          >
            {t.label}
          </button>
        ))}
        {hidden.length ? (
          <div className="os-tab-more">
            <OsDropdown
              className={cn('os-tab', moreActive && 'is-active')}
              align="end"
              width={220}
              label={
                <>
                  More
                  <CrmIcon name="chevron-down" className="iconSize-16" />
                </>
              }
            >
              {(close) => (
                <div role="menu">
                  {hidden.map((t) => (
                    <button
                      key={t.id}
                      type="button"
                      className={cn('os-menu__item', t.id === active && 'is-active')}
                      role="menuitem"
                      onClick={() => {
                        onSelect(t.id);
                        close();
                      }}
                    >
                      {t.label}
                    </button>
                  ))}
                </div>
              )}
            </OsDropdown>
          </div>
        ) : null}
      </nav>
    </div>
  );
}

/** Scrolls a sideways-scrolling tab row just enough to show `el` in full. */
function revealTab(nav: HTMLElement, el: HTMLElement) {
  const box = nav.getBoundingClientRect();
  const r = el.getBoundingClientRect();
  if (r.left < box.left) nav.scrollLeft -= box.left - r.left;
  else if (r.right > box.right) nav.scrollLeft += r.right - box.right;
}
