/**
 * Tabs Component
 * Tab navigation component
 */

'use client';

import { useState } from 'react';

export function Tabs({ children, defaultTab, value, onChange, className = '' }) {
  const [internalActiveTab, setInternalActiveTab] = useState(defaultTab || (children?.[0]?.props?.id || ''));
  
  // Use controlled value if provided, otherwise use internal state
  const activeTab = value !== undefined ? value : internalActiveTab;
  const setActiveTab = (tab) => {
    if (onChange) {
      onChange(tab);
    } else {
      setInternalActiveTab(tab);
    }
  };

  const tabs = children?.filter(child => child?.props?.id) || [];
  const activeTabContent = tabs.find(tab => tab.props.id === activeTab);

  return (
    <div className={className}>
      {/* Tab Headers */}
      <div className="border-b border-gray-200 dark:border-gray-700">
        <nav className="-mb-px flex space-x-8 overflow-x-auto" aria-label="Tabs">
          {tabs.map((tab) => {
            const isActive = activeTab === tab.props.id;
            return (
              <button
                key={tab.props.id}
                onClick={() => setActiveTab(tab.props.id)}
                className={`
                  whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm transition-colors
                  ${
                    isActive
                      ? 'border-blue-500 text-blue-600 dark:text-blue-400'
                      : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 dark:text-gray-400 dark:hover:text-gray-300'
                  }
                `}
                aria-current={isActive ? 'page' : undefined}
              >
                {tab.props.label}
                {tab.props.badge && (
                  <span className="ml-2 inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200">
                    {tab.props.badge}
                  </span>
                )}
              </button>
            );
          })}
        </nav>
      </div>

      {/* Tab Content */}
      <div className="mt-6">
        {activeTabContent}
      </div>
    </div>
  );
}

export function Tab({ id, label, badge, children }) {
  return <div id={id}>{children}</div>;
}
