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

export interface Tab {
  id: string;
  name: string;
  isActive: 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="h-10 bg-[#0a0a0a] border-b border-[#2a2a2a] flex items-center px-2 gap-1">
      {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-[#111111] border-b-[#0a0a0a] -mb-px border-t border-l border-r border-[#2a2a2a]'
              : 'bg-[#0a0a0a] hover:bg-[#1a1a1a] 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-[#58a6ff]' : 'text-[#888888]'}`} 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="bg-[#1a1a1a] border border-[#58a6ff] rounded px-1.5 py-0.5 text-xs font-mono text-[#e0e0e0] outline-none w-28"
              onClick={(e) => e.stopPropagation()}
            />
          ) : (
            <span className={`text-xs font-mono truncate max-w-[100px] ${tab.isActive ? 'text-[#e0e0e0]' : 'text-[#888888]'}`}>
              {tab.name}
            </span>
          )}

          {/* Close Button */}
          <button
            onClick={(e) => {
              e.stopPropagation();
              onTabClose(tab.id);
            }}
            className={`opacity-0 group-hover:opacity-100 flex-shrink-0 p-0.5 rounded hover:bg-[#2a2a2a] transition-all ${
              tab.isActive ? 'opacity-100' : ''
            }`}
            title="Close tab"
          >
            <svg className="w-3 h-3 text-[#888888] hover:text-[#e0e0e0]" 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 items-center justify-center w-7 h-7 rounded hover:bg-[#1a1a1a] text-[#888888] hover:text-[#e0e0e0] transition-colors flex-shrink-0"
        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>
  );
};
