import React, { useState, useEffect } from 'react'
import { Tab } from './components/Tab'
import { classNames } from '../utils/css'
import '../tailwind.css'


export interface TabsConfig {
    /* Label to display */
    label: string
    /* Id of the tab */
    id: string
}

export interface TabsProps {
    /* Tabs configuration */
    tabs: TabsConfig[]
    /** Callback when tab is selected */
    onSelect?(index: number): void
    /* Index number of selected tab */
    selected?: number
}

const styles = {
    tabs: 'w-full relative flex space-x-4 items-center justify-center bg-secondary-background rounded-lg',
    tab: 'w-full font-semibold text-center text-base text-gray-500 hover:text-gray-700 px-3 py-3 my-1 mx-1 font-medium rounded-lg cursor-pointer',
    active: 'bg-white text-primary hover:text-transparent'
}


export const Tabs = ({ tabs, onSelect, selected }: TabsProps) => {
    const [activeTab, setActiveTab] = useState(0)

    const TabStyles = (index: number, activeTab: number
    ) => {
        console.log(index)
        return classNames(
            ...[
                styles.tab,
                index === activeTab && styles.active
            ]
        )
    }

    useEffect(() => {
        const preSelected = selected ? selected : 0
        setActiveTab(preSelected)
    }, [])

    const onActiveTab = (index: number) => {
        setActiveTab(index)
        if (onSelect) {
            onSelect(index)
        }
    }

    const AllTabs = tabs.map((tab, index) => {
        const isObject = typeof tab === 'object'
        let label = isObject ? tab.label : tab
        let id = isObject ? tab.id : tab

        return (
            <div
                key={`${id}-${index}`}
                className={TabStyles(index, activeTab)}
                onClick={() => {
                    onActiveTab(index)
                }}
            >
                {label}
            </div>
        )
    })

    return <div className={styles.tabs}>{AllTabs}</div>
}

Tabs.Tab = Tab