import React, { useContext } from 'react';

import Tabs from '@digigov/react-core/Tabs';
import {
  TabsListItemBase,
  TabsListItemBaseProps,
} from '@digigov/react-core/TabsListItemBase';
import {
  TabsPanelBase,
  TabsPanelBaseProps,
} from '@digigov/react-core/TabsPanelBase';
import {
  useTabs,
  UseTabsReturn,
  TabId,
} from '@digigov/ui/navigation/Tabs/hooks';

export interface TabsListItemProps extends TabsListItemBaseProps {
  id: string;
}

export interface TabsPanelProps extends TabsPanelBaseProps {
  tab: TabId;
}

export const TabsContext = React.createContext<UseTabsReturn | null>(null);

export const useTabsContext = () => {
  const context = useContext(TabsContext);
  return context;
};

export const TabsAuto = ({ defaultOpen, children, ...props }) => {
  const tabs = useTabs({ defaultOpen });
  return (
    <TabsContext.Provider value={tabs}>
      <Tabs {...props}>{children}</Tabs>
    </TabsContext.Provider>
  );
};

export const TabsListItem = React.forwardRef<
  HTMLAnchorElement,
  TabsListItemProps
>(function TabsListItem({ ...props }, ref) {
  const context = useTabsContext();
  if (!context) {
    return <TabsListItemBase {...props} ref={ref} />;
  }
  return (
    <TabsListItemBase {...context.register(props.id)} ref={ref} {...props} />
  );
});

export const TabsPanel = React.forwardRef<HTMLDivElement, TabsPanelProps>(
  function TabsPanel({ tab, ...props }, ref) {
    const context = useTabsContext();
    if (!context) {
      return <TabsPanelBase ref={ref} {...props} />;
    }
    return <TabsPanelBase {...context.panel(tab)} ref={ref} {...props} />;
  }
);
