import React, { useContext, createContext } from "react"
import {
  Tabs as ReachTabs,
  TabList as ReachTabList,
  Tab as ReachTab,
  TabPanels as ReachTabPanels,
  TabPanel as ReachTabPanel,
} from "@reach/tabs"
import cx from "classnames"

const byAxis = (axis, verticalPref, horizontalPref) => {
  return axis === "horizontal" ? horizontalPref : verticalPref
}

const TabContext = createContext()

export function Tab({
  children,
  className,
  isSelected,
  ...props
}) {
  const orientation = useContext(TabContext)
  className = cx(
    className,
    "block whitespace-no-wrap p-3 font-semibold text-sm text-left",
    {
      "text-gray-700 hover:text-gray-800": !isSelected,
      "border-b-2 border-transparent focus:outline-none": orientation === "horizontal",
      "focus:outline-blue rounded-sm": orientation === "vertical",
      "bg-gray-50 text-gray-800": isSelected && orientation === 'vertical',
      "border-red-500 text-red-500": isSelected && orientation === 'horizontal',
    }
  )

  return (
    <ReachTab className={className} style={{ minWidth: byAxis(orientation, "100px", null) }} {...props}>
      {children}
    </ReachTab>
  )
}

export function Tabs({ children, className, orientation = "vertical", ...props }) {
  className = cx(className, byAxis(orientation,"flex",""))

  return (
    <ReachTabs className={className} {...props} orientation={orientation}>
      <TabContext.Provider value={orientation}>
        {children}
      </TabContext.Provider>
    </ReachTabs>
  )
}

export function TabList({ children, className, ...props }) {
  const orientation = useContext(TabContext)
  className = cx(className, byAxis(orientation, "flex-col", "flex"))

  return (
    <ReachTabList className={className} {...props}>
      {children}
    </ReachTabList>
  )
}

export function TabPanels({ children, className, ...props }) {
  const orientation = useContext(TabContext)
  className = cx(className, byAxis(orientation, "flex-grow", ""))

  return (
    <ReachTabPanels className={className} {...props}>
      {children}
    </ReachTabPanels>
  )
}

export function TabPanel({ children, className, ...props }) {
  className = cx(className, "focus:outline-none")

  return (
    <ReachTabPanel className={className} {...props}>
      {children}
    </ReachTabPanel>
  )
}
