/**
 * @Author: ??
 * @Date: ??
 */
import React, { useCallback } from "react"
import { TabsProps, TabsPaneProps } from "./interface"
import clsx from "clsx"
import "./index.css"

export const TabPane: React.FC<TabsPaneProps> = props => {
  const { children } = props
  return children
}

const TabPaneOverLoad = (props: any) => {
  const { tabKey, tab, active, orientation, onChange, className = "" } = props

  const classnames = clsx(
    "nts-tab-item",
    {
      ["nts-tab-item-horizontal"]: orientation === "horizontal",
      ["nts-tab-item-horizontal-active"]: active && orientation === "horizontal",

      ["nts-tab-item-vertical"]: orientation === "vertical",
      ["nts-tab-item-vertical-active"]: active && orientation === "vertical",

      ["nts-tab-item-active"]: active
    },
    className
  )

  const onTabChange = useCallback(() => onChange?.(tabKey), [])

  return (
    <div className={classnames} onClick={onTabChange}>
      {tab}
    </div>
  )
}

/**
 * ### 引用方法
 * ```tsx
 * import { Tabs } from "@atomintl/exchange-ui";
 * const TabPane = Tabs.TabPane;
 * ```
 */
export const Tabs: React.FC<TabsProps> & { TabPane: React.FC<TabsPaneProps> } = props => {
  const { children, defaultActiveKey, activeKey, orientation, classes, onChange, endTabComp } = props

  const classnames = clsx(
    {
      ["nts-tabs-horizontal"]: orientation === "horizontal",
      ["nts-tabs-vertical"]: orientation === "vertical"
    },
    classes?.root
  )

  return (
    <>
      <div className={classnames}>
        {React.Children.map(children, child => {
          const _active = child?.key == (activeKey || defaultActiveKey)
          return (
            <TabPaneOverLoad
              tabKey={child?.key}
              tab={(child.props as TabsPaneProps)?.tab}
              active={_active}
              orientation={orientation}
              onChange={onChange}
              className={classes?.tab}
            />
          )
        })}
        {endTabComp}
      </div>
      {/* <div className="border-t"></div> */}
      {React.Children.map(children, child => {
        if (child?.key == (activeKey || defaultActiveKey)) {
          if (!React.isValidElement(child)) return child
          return React.cloneElement(child, { ...(child.props as TabsPaneProps) })
        }
      })}
    </>
  )
}

Tabs.TabPane = TabPane
Tabs.defaultProps = { orientation: "horizontal" }

export type { TabsProps, TabsPaneProps }
export default Tabs
