import { createContext, useContext, useState } from '@wordpress/element';
import classNames from 'classnames';
import { TabPanel } from '@wordpress/components';

const TabsContext = createContext<{
  activeTab: string | undefined;
  setActiveTab: React.Dispatch<React.SetStateAction<string | undefined>>;
} | null>(null);

type TabsProps = {
  className?: string;
  defaultValue?: string;
  value?: string;
  onValueChange?: (value: string) => void;
  children?: React.ReactNode;
};

export const TabsWrapper = ({
  children,
  defaultValue,
  value,
  onValueChange,
  ...rest
}: TabsProps) => {
  const [activeTab, setActiveTab] = useState(defaultValue || '');
  const providerValue = {
    activeTab,
    setActiveTab,
  };

  if (value && onValueChange) {
    providerValue.activeTab = value;
    providerValue.setActiveTab = onValueChange;
  }

  return (
    <TabsContext.Provider value={providerValue}>
      <div className={rest.className || ''}>{children}</div>
    </TabsContext.Provider>
  );
};

type TabsListProps = {
  options: { name: string; title: string; icon?: any }[];
  children?: React.ReactNode;
  onValueChange?: (value: string) => void;
  className?: string;
};

export const TabsList = ({
  options,
  children,
  className,
  onValueChange,
}: TabsListProps) => {
  const context = useContext(TabsContext);
  const setActiveTab = onValueChange ? onValueChange : context?.setActiveTab;

  return (
    <TabPanel
      className={classNames('tabs-list', className)}
      tabs={options}
      onSelect={(tabName) => {
        setActiveTab(tabName);
      }}
    >
      {() => children}
    </TabPanel>
  );
};

type TabsContentProps = {
  value: string;
  children: React.ReactNode;
  className?: string;
};

export const TabsContent = ({
  value,
  children,
  className,
}: TabsContentProps) => {
  const context = useContext(TabsContext);
  const activeTab = context?.activeTab;

  return activeTab === value ? (
    <div className={className}>{children}</div>
  ) : null;
};
