/**
 * References:
 * - https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Reference/Roles/tablist_role
 * - https://www.w3.org/WAI/ARIA/apg/patterns/tabs/
 *
 *
 * Keyboard behaviors (optionally) provided by tabster
 */

import Component from "@glimmer/component";
import { tracked } from "@glimmer/tracking";
import { isDestroyed, isDestroying } from "@ember/destroyable";
import { fn } from "@ember/helper";
import { on } from "@ember/modifier";
import { next } from "@ember/runloop";

import { getTabsterAttribute, MoverDirections } from "tabster";

import { uniqueId } from "../utils.ts";
import Portal from "./portal.gts";

import type { TOC } from "@ember/component/template-only";
import type Owner from "@ember/owner";
import type { ComponentLike, WithBoundArgs } from "@glint/template";

const UNSET = Symbol.for("ember-primitives:tabs:unset");

const TABSTER_CONFIG = getTabsterAttribute(
  {
    mover: {
      direction: MoverDirections.Both,
      cyclic: true,
      hasDefault: true,
      memorizeCurrent: true,
    },
    deloser: {},
  },
  true,
);

const TABSTER_SELECTED_TAB = getTabsterAttribute({ focusable: { isDefault: true } }, true);

function tabsterFor(isSelected: boolean) {
  return isSelected ? TABSTER_SELECTED_TAB : undefined;
}

const TabLink: TOC<{
  Element: HTMLAnchorElement;
  Args: {
    /**
     * @internal
     * for linking of aria
     */
    id: string;
    /**
     * @internal
     * for linking of aria
     */
    panelId: string;

    /**
     * @internal
     * for managing state
     */
    value: string | undefined;

    /**
     * @internal
     */
    state: TabState;
  };
  Blocks: { default: [] };
}> = <template>
  <a
    href="##missing##"
    ...attributes
    role="tab"
    aria-controls={{@panelId}}
    aria-selected={{String (@state.isActive @id @value)}}
    id={{@id}}
  >
    {{yield}}
  </a>
</template>;

export type ButtonType = ComponentLike<ButtonSignature>;
export interface ButtonSignature {
  Element: HTMLButtonElement;
  Blocks: {
    default: [];
  };
}

const TabButton: TOC<{
  Element: HTMLButtonElement;
  Args: {
    /**
     * @internal
     * for linking of aria
     */
    id: string;
    /**
     * @internal
     * for linking of aria
     */
    panelId: string;

    /**
     * @internal
     * for managing state
     */
    handleClick: () => void;

    /**
     * @internal
     * for managing state
     */
    value: string | undefined;

    /**
     * @internal
     */
    state: TabState;
  };
  Blocks: {
    default: [];
  };
}> = <template>
  <button
    ...attributes
    role="tab"
    type="button"
    aria-controls={{@panelId}}
    aria-selected={{String (@state.isActive @id @value)}}
    data-tabster={{tabsterFor (@state.isActive @id @value)}}
    id={{@id}}
    {{on "click" @handleClick}}
    {{! The Types for modifier are wrong }}
    {{! @glint-expect-error}}
    {{(if @state.isAutomatic (modifier on "focus" @handleClick))}}
  >
    {{yield}}
  </button>
</template>;

export type ContentType = ComponentLike<ContentSignature>;
export interface ContentSignature {
  /**
   * the [role=tabpanel] element
   */
  Element: HTMLDivElement;
  Blocks: {
    default: [];
  };
}

const TabContent: TOC<{
  Element: HTMLDivElement;
  Args: {
    /**
     * @internal
     * for linking of aria
     */
    id: string;
    /**
     * @internal
     * for linking of aria
     */
    tabId: string;
    /**
     * @internal
     */
    state: TabState;
  };
  Blocks: {
    default: [];
  };
}> = <template>
  {{#if (@state.isActive @tabId)}}
    <div tabindex="0" ...attributes role="tabpanel" aria-labelledby={{@tabId}} id={{@id}}>
      {{yield}}
    </div>
  {{/if}}
</template>;

/**
 * Stands in for a part of a tab that the current pass does not render.
 */
const Nothing: TOC<{
  Element: HTMLButtonElement & HTMLAnchorElement & HTMLDivElement;
  Blocks: { default: [] };
}> = <template></template>;

function isString(x: unknown): x is string {
  return typeof x === "string";
}

function makeTab(tabButton: any, tabLink: any): any {
  // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
  tabButton.Link = tabLink;

  return tabButton;
}

export type ContainerType = ComponentLike<ContainerSignature>;
export type ContainerSignature =
  | {
      Blocks: {
        default: [];
      };
    }
  | {
      Args: {
        label: string | ComponentLike;
        content: string | ComponentLike;
      };
    }
  | {
      Args: {
        label: string | ComponentLike;
      };
      Blocks: {
        /**
         * The content for the tab
         */
        default: [];
      };
    };

class TabContainer extends Component<{
  Args: {
    /**
     * @internal
     */
    state: TabState;

    /**
     * @internal
     * true when this instance renders the panel, false when it renders the tab
     */
    inPanel?: boolean;

    /**
     * When opting for a "controlled component",
     * the value will be needed to make sense of the selected tab.
     *
     * The default value used for communication within the Tabs component (and eventually emitted via the @onChange argument) is a unique random id.
     * So while that could still be used for controlling the tabs component, it may be more easy to grok with user-managed values.
     */
    value?: string;

    /**
     * optional user-passable label
     */
    label?: string | ComponentLike;

    /**
     * optional user-passable content.
     */
    content?: string | ComponentLike;
  };
  Blocks: {
    default: [
      Label: WithBoundArgs<
        typeof TabButton,
        "state" | "id" | "panelId" | "handleClick" | "value"
      > & {
        Link: WithBoundArgs<typeof TabLink, "state" | "value" | "id" | "panelId">;
      },
      Content: WithBoundArgs<typeof TabContent, "state" | "id" | "tabId">,
    ];
  };
}> {
  id = this.args.state.nextTabId(this.args.inPanel ?? false);

  get tabId() {
    return `${this.id}__tab`;
  }

  get panelId() {
    return `${this.id}__panel`;
  }

  get label() {
    return this.args.label ?? this.tabId;
  }

  <template>
    {{!
      <Tabs> renders its block two times, and each <Tab> renders one time in each pass:

        1. the tablist pass (@inPanel is false), which renders only the tab button
        2. the tabpanel pass (@inPanel is true), which renders only the panel

      A user can invoke <Tab> in three ways:

        <Tab @label="npm" @content="npm add ember-primitives" />

        <Tab @label="npm">npm add ember-primitives</Tab>

        <Tab as |Label Content|>
          <Label>npm</Label>
          <Content>npm add ember-primitives</Content>
        </Tab>

      The first two ways pass @label, and the third way does not.
      So each pass has one branch for @label and one branch for the yielded block.

      Why two passes:
      before, the panel rendered through a Portal into the tabpanel element.
      The Portal finds its target in a modifier, so the panel appeared only in a second render.
      When the client rehydrated server-rendered HTML, the first client render had no panel.
      Rehydration then deleted the server panel, and the second render built it again.
      The user saw the panel flash.
    }}
    {{#if @inPanel}}
      {{!
        Tabpanel pass of:
          <Tab @label="npm" @content="npm add ember-primitives" />
          <Tab @label="npm">npm add ember-primitives</Tab>

        The @label renders in the tablist pass, so this branch ignores it.
      }}
      {{#if @label}}
        <TabContent @state={{@state}} @id={{this.panelId}} @tabId={{this.tabId}}>
          {{#if @content}}
            {{#if (isString @content)}}
              {{@content}}
            {{else}}
              <@content />
            {{/if}}
          {{else}}
            {{yield}}
          {{/if}}
        </TabContent>
      {{else}}
        {{!
          Tabpanel pass of:
            <Tab as |Label Content|>
              <Label>npm</Label>
              <Content>npm add ember-primitives</Content>
            </Tab>

          The block runs again in this pass, so it calls <Label> (or <Label.Link>) again.
          (makeTab Nothing Nothing) makes <Label> and <Label.Link> render nothing here.

          Without Nothing, each tab button renders a second time, inside the tabpanel element.
          The page then has two elements with the same id, and a role="tab" outside of the tablist.
        }}
        {{yield
          (makeTab Nothing Nothing)
          (component TabContent state=@state id=this.panelId tabId=this.tabId)
        }}
      {{/if}}
    {{else if @label}}
      {{!
        Tablist pass of:
          <Tab @label="npm" @content="npm add ember-primitives" />
          <Tab @label="npm">npm add ember-primitives</Tab>

        This branch does not yield, so the content renders only in the tabpanel pass.
      }}
      <TabButton
        @state={{@state}}
        @id={{this.tabId}}
        @value={{@value}}
        @panelId={{this.panelId}}
        @handleClick={{fn @state.handleChange this.tabId @value}}
      >
        {{#if (isString @label)}}
          {{@label}}
        {{else}}
          <@label />
        {{/if}}
      </TabButton>
    {{else}}
      {{!
        Tablist pass of:
          <Tab as |Label Content|>
            <Label>npm</Label>
            <Content>npm add ember-primitives</Content>
          </Tab>

        The block calls <Content> in this pass too, so Content is Nothing here.
        Without Nothing, the panel renders inside the tablist element,
        where only role="tab" elements are valid, and it renders a second time in the tabpanel pass.
      }}
      {{yield
        (makeTab
          (component
            TabButton
            state=@state
            value=@value
            id=this.tabId
            panelId=this.panelId
            handleClick=(fn @state.handleChange this.tabId @value)
          )
          (component TabLink state=@state value=@value id=this.tabId panelId=this.panelId)
        )
        Nothing
      }}
    {{/if}}
  </template>
}

const Label: TOC<{
  /**
   * The label wiring (id, aria, etc) are handled for you.
   * If you'd like to use a heading element (h3, etc), place that in the block content
   * when invoking this Label component.
   */
  Element: null;
  Args: {
    /**
     * @internal
     */
    state: TabState;
  };
  Blocks: { default: [] };
}> = <template>
  <Portal @to="#{{@state.labelId}}">
    {{yield}}
  </Portal>
</template>;

export interface Signature {
  /**
   * The wrapping element for the overall Tabs component.
   * This should be used for styling the layout of the tabs.
   */
  Element: HTMLDivElement;
  Args: {
    /**
     * Sets the active tab.
     * If not passed, the first tab will be selected
     */
    activeTab?: string;

    /**
     * Optional label for the overall TabList
     */
    label?: string | ComponentLike;

    /**
     * When the tab changes, this function will be called.
     * The function receives both the newly selected tab as well as the previous tab.
     *
     * However, if the tabs are not configured with names, these values will be null.
     */
    onChange?: (selectedTab: string, previousTab: string | null) => void;

    /**
     * When activationMode is set to "automatic", tabs are activated when receiving focus. When set to "manual", tabs are activated when clicked (or when "enter" is pressed via the keyboard).
     */
    activationMode?: "automatic" | "manual";
  };
  Blocks: {
    default: [
      Tab: WithBoundArgs<typeof TabContainer, "state"> & {
        Label: WithBoundArgs<typeof Label, "state">;
      },
    ];
  };
}

/**
 * We're doing old skool hax with this, so we don't need to care about what the types think, really
 */
function makeAPI(tabContainer: any, labelComponent: any): any {
  // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment
  tabContainer.Label = labelComponent;

  return tabContainer;
}

import { buildWaiter } from "@ember/test-waiters";

const stateWaiter = buildWaiter("ember-primitives:tabs");

/**
 * State bucket passed around to all the sub-components.
 *
 * Sort of a "Context", but with a bit of prop-drilling (which is more efficient than dom-context)
 */
class TabState {
  declare args: {
    activeTab?: string;
    activationMode?: "automatic" | "manual";
    onChange?: (selected: string, previous: string | null) => void;
  };

  @tracked _active: string | null = null;

  @tracked _label: string | undefined;

  #first: string | null = null;
  id: string;
  labelId: string;
  tabpanelId: string;
  #token: unknown;

  #tabCount = 0;
  #panelCount = 0;

  constructor(args: { activeTab?: string; onChange?: () => void }) {
    this.args = args;

    this.id = `ember-primitives-${uniqueId()}`;
    this.labelId = `${this.id}__label`;
    this.tabpanelId = `${this.id}__tabpanel`;
  }

  /**
   * The block of <Tabs> renders two times:
   * one time in the tablist for the tabs,
   * and one time after the tablist for the panels.
   *
   * The n-th tab and the n-th panel get the same id,
   * so that the aria attributes link them.
   */
  nextTabId(inPanel: boolean) {
    const index = inPanel ? this.#panelCount++ : this.#tabCount++;

    return `${this.id}__tab-${index}`;
  }

  get activationMode() {
    return this.args.activationMode ?? "automatic";
  }

  get isAutomatic() {
    return this.activationMode === "automatic";
  }

  /**
   * This function relies on the fact that during rendering,
   * the first component to be rendered will be first,
   * and it will be the one to set the secret first value,
   * which means all other tabs will not be first.
   *
   */
  isActive = (tabId: string, tabValue: undefined | string) => {
    /**
     * When users pass the @value to a tab, we use that for managing
     * the "active state" instead of the DOM ID.
     *
     * NOTE: DOM IDs must be unique across the whole document, but @value
     *     does not need to be unqiue.
     *          `@value` *should* be unique for the Tabs component though
     */
    const isSelected = (x: string) => {
      if (tabValue) return x === tabValue;

      return x === tabId;
    };

    if (this.active === UNSET) {
      if (this.#first) return isSelected(this.#first);

      this.#first = tabValue ?? tabId;
      this.#token = stateWaiter.beginAsync();

      // eslint-disable-next-line ember/no-runloop
      next(() => {
        if (!this.#token) return;
        stateWaiter.endAsync(this.#token);
        if (this._active) return;
        if (isDestroyed(this) || isDestroying(this)) return;

        this._label = tabValue ?? tabId;
      });

      return true;
    }

    return isSelected(this.active);
  };

  get active() {
    return this._active ?? this.args.activeTab ?? UNSET;
  }

  get activeLabel() {
    /**
     * This is only needed during the first set
     * because we prioritize rendering first, and then updating metadata later
     * (next render)
     *
     * NOTE: this does not mean that the a11y tree is updated later.
     *       it is correct on initial render
     */
    if (this._label) {
      return this._label;
    }

    if (this.active === UNSET) {
      return "Pending";
    }

    return this.active;
  }

  handleChange = (tabId: string, tabValue: string | undefined) => {
    const previous = this.active;
    const next = tabValue ?? tabId;

    // No change, no need to be noisy
    if (next === previous) return;

    this._active = this._label = next;

    this.args.onChange?.(next, previous === UNSET ? null : previous);
  };
}

export class Tabs extends Component<Signature> {
  state: TabState;

  // eslint-disable-next-line @typescript-eslint/no-empty-object-type
  constructor(owner: Owner, args: {}) {
    super(owner, args);

    this.state = new TabState(args);
  }

  <template>
    <div class="ember-primitives__tabs" ...attributes data-active={{this.state.activeLabel}}>
      {{! This element will be portaled in to and replaced if tabs.Label is invoked }}
      <div class="ember-primitives__tabs__label" id={{this.state.labelId}}>
        {{#if (isString @label)}}
          {{@label}}
        {{else}}
          <@label />
        {{/if}}
      </div>
      <div
        class="ember-primitives__tabs__tablist"
        role="tablist"
        aria-labelledby={{this.state.labelId}}
        data-tabster={{TABSTER_CONFIG}}
      >
        {{yield
          (makeAPI (component TabContainer state=this.state) (component Label state=this.state))
        }}
      </div>
      {{!
        The block renders again here for the panels,
        so that the panels are in the first render, without a second pass.
        That keeps the DOM of a server render when the client rehydrates it.
        In this pass, the <Tabs> Label (the label of the whole tablist) is Nothing,
        because the first pass already rendered it.
        Without Nothing, a block that calls <Label> renders the label two times.
      }}
      <div class="ember-primitives__tabs__tabpanel" id={{this.state.tabpanelId}}>
        {{yield
          (makeAPI (component TabContainer state=this.state inPanel=true) (component Nothing))
        }}
      </div>
    </div>
  </template>
}
