import React, { useState, useRef, useEffect } from 'react';

export interface Tab {
  id: string;
  name: string;
  isActive: boolean;
  portfolioName?: string | null;
  isProcessing?: boolean;
  hasPendingApproval?: boolean;
}

interface TabBarProps {
  tabs: Tab[];
  onTabClick: (id: string) => void;
  onTabClose: (id: string) => void;
  onNewTab: () => void;
  onTabRename?: (id: string, newName: string) => void;
}

export const TabBar: React.FC<TabBarProps> = ({
  tabs,
  onTabClick,
  onTabClose,
  onNewTab,
  onTabRename
}) => {
  const [editingId, setEditingId] = useState<string | null>(null);
  const [editValue, setEditValue] = useState('');
  const editInputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (editingId && editInputRef.current) {
      editInputRef.current.focus();
      editInputRef.current.select();
    }
  }, [editingId]);

  const handleDoubleClick = (tab: Tab) => {
    setEditingId(tab.id);
    setEditValue(tab.name);
  };

  const handleEditSubmit = () => {
    if (editingId && editValue.trim() && onTabRename) {
      onTabRename(editingId, editValue.trim());
    }
    setEditingId(null);
    setEditValue('');
  };

  const handleEditKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      handleEditSubmit();
    } else if (e.key === 'Escape') {
      setEditingId(null);
      setEditValue('');
    }
  };

  return (
    <div className="flex h-10 items-center gap-1 border-b border-term-border bg-term-bg px-2">
      {tabs.map((tab) => (
        <div
          key={tab.id}
          className={`group flex items-center gap-1.5 px-2 py-1 rounded-t tab-transition cursor-pointer border border-transparent ${
            tab.isActive
              ? 'bg-term-elevated border-b-term-bg -mb-px border-t border-l border-r border-term-border'
              : 'bg-term-bg hover:bg-term-surface border-t border-l border-r border-transparent'
          }`}
          onClick={() => !editingId && onTabClick(tab.id)}
          onDoubleClick={() => !editingId && handleDoubleClick(tab)}
        >
          {/* Terminal Icon */}
          <svg className={`w-3 h-3 flex-shrink-0 ${tab.isActive ? 'text-info' : 'text-term-text-tertiary'}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 9l3 3-3 3m5 0h3M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
          </svg>

          {/* Tab Name or Edit Input */}
          {editingId === tab.id ? (
            <input
              ref={editInputRef}
              type="text"
              value={editValue}
              onChange={(e) => setEditValue(e.target.value)}
              onBlur={handleEditSubmit}
              onKeyDown={handleEditKeyDown}
              className="w-28 rounded border border-info bg-term-surface px-1.5 py-0.5 text-xs font-mono text-term-text outline-none"
              onClick={(e) => e.stopPropagation()}
            />
          ) : (
            <div className="flex flex-col">
              <div className="flex items-center gap-1.5">
                <span className={`max-w-[100px] truncate text-xs font-mono ${tab.isActive ? 'text-term-text' : 'text-term-text-muted'}`}>
                  {tab.name}
                </span>
                {tab.isProcessing ? (
                  <span className="inline-flex h-2 w-2 rounded-full bg-info animate-pulse" />
                ) : null}
                {tab.hasPendingApproval ? (
                  <span className="inline-flex h-2 w-2 rounded-full bg-warning" />
                ) : null}
              </div>
              {tab.portfolioName && (
                <span className={`max-w-[100px] truncate text-[9px] font-mono ${tab.isActive ? 'text-info' : 'text-term-text-tertiary'}`}>
                  {tab.portfolioName}
                </span>
              )}
            </div>
          )}

          {/* Close Button */}
          <button
            onClick={(e) => {
              e.stopPropagation();
              onTabClose(tab.id);
            }}
            className={`opacity-0 group-hover:opacity-100 flex-shrink-0 rounded p-0.5 transition-all hover:bg-term-highlight ${
              tab.isActive ? 'opacity-100' : ''
            }`}
            title="Close tab"
          >
            <svg className="w-3 h-3 text-term-text-tertiary hover:text-term-text" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>
      ))}

      {/* New Tab Button */}
      <button
        onClick={onNewTab}
        className="flex h-7 w-7 flex-shrink-0 items-center justify-center rounded text-term-text-tertiary transition-colors hover:bg-term-surface hover:text-term-text"
        title="New terminal (Cmd+T)"
      >
        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
        </svg>
      </button>
    </div>
  );
};
