import React from 'react';
import { Tabs as MuiTabs, TabsActions, TabsClasses, TabScrollButtonProps } from '@mui/material';
import { Tab, TabProps } from './tab';
import { TabContext, TabsContext } from '../types/tabs.type';
import { TabPanel } from './panel';
import { PanelsContainer, TabsContainer } from './style';

export interface TabsProps {
    style?: React.CSSProperties,
    action?: React.Ref<TabsActions>;
    allowScrollButtonsMobile?: boolean;
    centered?: boolean;
    classes?: Partial<TabsClasses>;
    indicatorColor?: 'secondary' | 'primary';
    onChange?: (index: number) => void;
    orientation?: 'horizontal' | 'vertical';
    ScrollButtonComponent?: React.ElementType;
    scrollButtons?: 'auto' | true | false;
    selectionFollowsFocus?: boolean;
    TabIndicatorProps?: React.HTMLAttributes<HTMLDivElement>;
    TabScrollButtonProps?: Partial<TabScrollButtonProps>;
    textColor?: 'secondary' | 'primary' | 'inherit';
    value?: number;
    variant?: 'standard' | 'scrollable' | 'fullWidth';
    visibleScrollbar?: boolean;
    children?: React.ReactElement<TabProps>[] | React.ReactElement<TabProps>,
}

export const Tabs: React.FC<TabsProps> = ({ style, value, onChange, children, ...props }) => {
    const header = React.useRef<any>();
    const [selected, setSelected] = React.useState(value ? value : 0);
    const [context] = React.useState<TabsContext>({
        tabs: []
    });
    const [forceUpdate, setForceUpdate] = React.useState(false);

    React.useEffect(() => {
        if (children) {
            const tabs: TabContext[] = [];

            React.Children.map<void, React.ReactElement>(children, child => {
                if (child.type === Tab) {
                    tabs.push({
                        selector: child,
                        content: child.props.children
                    })
                }
            })
            context.tabs = tabs;
            setForceUpdate(!forceUpdate);
        }
    }, [children])

    const handleSelectionChange = (event: React.SyntheticEvent, newValue: number) => {
        setSelected(newValue);

        if (onChange) {
            onChange(newValue);
        }
    };

    return (
        <TabsContainer style={style}>
            <MuiTabs {...props} value={selected} onChange={handleSelectionChange} ref={header}>
                {children}
            </MuiTabs>
            <PanelsContainer style={{height: header.current ? `calc(100% - ${header.current.clientHeight}px)` : 'calc(100% - 50px)'}}>
                {
                    context.tabs.map((tab, index) => (
                        <TabPanel key={`${index}`} index={index} selected={selected}>
                            {tab.content}
                        </TabPanel>
                    ))
                }
            </PanelsContainer>
        </TabsContainer>
    )
}