"use client";

import React, { useMemo, useState } from 'react';

export type TabItem = {
  key: string;
  title: React.ReactNode;
  content: React.ReactNode;
  disabled?: boolean;
};

export type TabsProps = {
  items: TabItem[];
  defaultActiveKey?: string;
  activeKey?: string;
  onChange?: (key: string) => void;
  variant?: 'tabs' | 'pills';
  fill?: boolean;
  justify?: boolean;
  className?: string;
  navClassName?: string;
  contentClassName?: string;
};

export function Tabs({
  items,
  defaultActiveKey,
  activeKey,
  onChange,
  variant = 'tabs',
  fill,
  justify,
  className = '',
  navClassName = '',
  contentClassName = ''
}: TabsProps) {
  const fallbackKey = items.find(i => !i.disabled)?.key;
  const [internalKey, setInternalKey] = useState<string | undefined>(defaultActiveKey ?? fallbackKey);
  const currentKey = activeKey ?? internalKey ?? fallbackKey;

  const navClasses = useMemo(() => {
    return [
      'nav',
      variant === 'tabs' ? 'nav-tabs' : 'nav-pills',
      fill ? 'nav-fill' : '',
      justify ? 'nav-justified' : '',
      navClassName
    ]
      .filter(Boolean)
      .join(' ');
  }, [variant, fill, justify, navClassName]);

  const handleSelect = (key: string, disabled?: boolean) => {
    if (disabled) return;
    if (!activeKey) {
      setInternalKey(key);
    }
    onChange?.(key);
  };

  return (
    <div className={className}>
      <ul className={navClasses}>
        {items.map(item => {
          const isActive = item.key === currentKey;
          return (
            <li className="nav-item" key={item.key}>
              <button
                type="button"
                className={`nav-link ${isActive ? 'active' : ''} ${item.disabled ? 'disabled' : ''}`.trim()}
                onClick={() => handleSelect(item.key, item.disabled)}
              >
                {item.title}
              </button>
            </li>
          );
        })}
      </ul>
      <div className={`tab-content ${contentClassName}`.trim()}>
        {items.map(item => {
          const isActive = item.key === currentKey;
          return (
            <div
              key={item.key}
              className={`tab-pane fade ${isActive ? 'show active' : ''}`.trim()}
              role="tabpanel"
            >
              {isActive ? item.content : null}
            </div>
          );
        })}
      </div>
    </div>
  );
}
