import { Children, Fragment, isValidElement } from 'react';
import { Tabs as BaseTabs } from '@base-ui/react/tabs';
import * as stylex from '@stylexjs/stylex';

import type { ReactElement } from 'react';
import type { TabProps, TabsProps } from './types';

import { Layout } from '~/src/ui/layouts/layout';
import { tabsStyles } from './styles';

export const Tab = ({ children }: TabProps) => {
  return <>{children}</>;
};

export const Tabs = ({
  children,
  testId,
  defaultTabId,
  onTabChange,
}: TabsProps) => {
  const tabs = Children.toArray(children).filter(
    (child): child is ReactElement<TabProps> =>
      isValidElement(child) &&
      (child.type === Tab ||
        (typeof child.type === 'function' && child.type.name === 'Tab'))
  );

  return (
    <BaseTabs.Root
      defaultValue={defaultTabId ?? tabs[0]?.props.id}
      onValueChange={
        onTabChange ? (value) => onTabChange(value as string) : undefined
      }
    >
      <Layout testId={testId} column gap="6">
        <BaseTabs.List {...stylex.props(tabsStyles.tabList)}>
          {tabs.map((tab, index) => (
            <Fragment key={tab.props.id}>
              <BaseTabs.Tab
                value={tab.props.id}
                render={(props) => (
                  <button
                    {...props}
                    {...stylex.props(
                      tabsStyles.tab,
                      props['aria-selected'] && tabsStyles.tabActive
                    )}
                  />
                )}
              >
                {tab.props.label}
              </BaseTabs.Tab>

              {index < tabs.length - 1 && (
                <div {...stylex.props(tabsStyles.separator)}>·</div>
              )}
            </Fragment>
          ))}
        </BaseTabs.List>

        {tabs.map((tab) => (
          <BaseTabs.Panel key={tab.props.id} value={tab.props.id}>
            {tab.props.children}
          </BaseTabs.Panel>
        ))}
      </Layout>
    </BaseTabs.Root>
  );
};
