import { __assign, __read, __rest } from "tslib";
import React, { useState, useEffect, forwardRef } from "react";
import Tab from "../Tab";
import { useTabContext } from "../TabContext";
import { TabsStyled } from "./styles";
var Tabs = forwardRef(function (_a, ref) {
    var items = _a.items, children = _a.children, className = _a.className, value = _a.value, size = _a.size, onChange = _a.onChange, props = __rest(_a, ["items", "children", "className", "value", "size", "onChange"]);
    var context = useTabContext();
    var _b = __read(useState(typeof value === "undefined" ? context === null || context === void 0 ? void 0 : context.value : value), 2), selected = _b[0], setSelected = _b[1];
    var handleChange = function (event, _value) {
        setSelected(_value);
        onChange === null || onChange === void 0 ? void 0 : onChange(event, _value);
        if (!value) {
            context === null || context === void 0 ? void 0 : context.onChange(_value);
        }
    };
    var getClassName = function (index, _value, _className) {
        return (_className || "") + " " + (_value === selected || (_value === undefined && index === selected)
            ? "tab_selected"
            : "");
    };
    useEffect(function () {
        setSelected(value);
    }, [value]);
    useEffect(function () {
        if (!value) {
            setSelected((context === null || context === void 0 ? void 0 : context.value) || selected);
        }
    }, [context === null || context === void 0 ? void 0 : context.value]);
    return (React.createElement(TabsStyled, __assign({ className: className, role: "tablist", ref: ref }, props), children
        ? React.Children.map(children, function (child, index) {
            return React.cloneElement(child, {
                size: size,
                className: getClassName(index, child.props.value, child.props.className),
                onClick: function (e) {
                    var _a, _b;
                    handleChange(e, child.props.value || index);
                    (_b = (_a = child.props).onClick) === null || _b === void 0 ? void 0 : _b.call(_a, e);
                }
            });
        })
        : items === null || items === void 0 ? void 0 : items.map(function (item, index) {
            if (typeof item === "string") {
                return (React.createElement(Tab, { size: size, key: item, label: item, className: index === selected ? "tab_selected" : "", onClick: function (event) { return handleChange(event, index); } }));
            }
            return (React.createElement(Tab, { size: size, key: item.label, label: item.label, className: getClassName(index, item.value), icon: item.icon, onClick: function (event) {
                    return handleChange(event, item.value || index);
                } }));
        })));
});
Tabs.displayName = "Tabs";
export default Tabs;
