import {
  createEffect,
  splitProps,
  type JSX,
  type ParentComponent,
} from "solid-js";
import { useTabListContext } from "./Tabs";
import "./Tab.css";

const Tab: ParentComponent<
  {
    focus?: boolean;
  } & JSX.ButtonHTMLAttributes<HTMLButtonElement>
> = (props) => {
  const [managed, rest] = splitProps(props, ["focus", "type", "role", "ref"]);
  let self: HTMLButtonElement;
  const {
    focusOn: [, setFocusOn],
  } = useTabListContext();

  createEffect<boolean | undefined>((lastStatus) => {
    if (managed.focus && !lastStatus) {
      setFocusOn((x) => [...x, self]);
    }
    if (!managed.focus && lastStatus) {
      setFocusOn((x) => x.filter((e) => e !== self));
    }
    return managed.focus;
  });

  return (
    <button
      ref={(x) => {
        self = x;
        (managed.ref as (e: HTMLButtonElement) => void)?.(x);
      }}
      type={managed.type ?? "button"}
      classList={{ Tab: true, focus: managed.focus }}
      role={managed.role ?? "tab"}
      {...rest}
    >
      {props.children}
    </button>
  );
};

export default Tab;
