import { useState, useRef, useCallback, memo } from 'react';
import { Plus, X, Columns, Grid2X2, Maximize2, GripVertical, Circle } from 'lucide-react';
import { useSessionManager } from '../contexts/SessionContext';

// Tab component
const Tab = memo(function Tab({
  session,
  isActive,
  isSplit,
  index,
  onDragStart,
  onDragOver,
  onDrop,
  onFocus,
  onClose,
  onSplit,
  onRename,
}) {
  const [isEditing, setIsEditing] = useState(false);
  const [editName, setEditName] = useState('');
  const inputRef = useRef(null);

  // Get display name
  const getDisplayName = () => {
    if (session.name) return session.name;

    // Auto-generate from host and context/project
    const hostName = session.host.charAt(0).toUpperCase() + session.host.slice(1);
    const context = session.currentContext || session.project.split('/').pop() || 'New';
    return `${hostName}: ${context}`;
  };

  // Get host color
  const getHostColor = () => {
    switch (session.host) {
      case 'neko': return '#f97316';
      case 'mochi': return '#22c55e';
      default: return '#6b7280';
    }
  };

  const handleDoubleClick = () => {
    setEditName(session.name || '');
    setIsEditing(true);
    setTimeout(() => inputRef.current?.select(), 0);
  };

  const handleRename = () => {
    if (editName.trim()) {
      onRename(session.id, editName.trim());
    }
    setIsEditing(false);
  };

  const handleKeyDown = (e) => {
    if (e.key === 'Enter') {
      handleRename();
    } else if (e.key === 'Escape') {
      setIsEditing(false);
    }
  };

  return (
    <div
      draggable={!isEditing}
      onDragStart={(e) => onDragStart(e, index)}
      onDragOver={onDragOver}
      onDrop={(e) => onDrop(e, index)}
      onClick={() => onFocus(session.id)}
      onDoubleClick={handleDoubleClick}
      className={`
        group flex items-center gap-2 px-3 py-2 rounded-t-lg cursor-pointer
        transition-colors relative min-w-[120px] max-w-[200px]
        ${isActive
          ? 'bg-dark-800 text-white border-t-2'
          : 'bg-dark-900/50 text-dark-400 hover:bg-dark-800/50 hover:text-dark-300 border-t-2 border-transparent'
        }
        ${isSplit ? 'ring-1 ring-inset ring-blue-500/30' : ''}
      `}
      style={{
        borderTopColor: isActive ? getHostColor() : 'transparent',
      }}
    >
      {/* Drag handle */}
      <GripVertical className="w-3 h-3 text-dark-600 opacity-0 group-hover:opacity-100 cursor-grab flex-shrink-0" />

      {/* Status indicator */}
      <div className="relative flex-shrink-0">
        <Circle
          className="w-2 h-2"
          fill={session.active ? '#22c55e' : session.connected ? '#f97316' : '#6b7280'}
          stroke="none"
        />
        {session.isProcessing && (
          <span className="absolute inset-0 w-2 h-2 rounded-full bg-orange-400 animate-ping" />
        )}
      </div>

      {/* Tab name */}
      {isEditing ? (
        <input
          ref={inputRef}
          type="text"
          value={editName}
          onChange={(e) => setEditName(e.target.value)}
          onBlur={handleRename}
          onKeyDown={handleKeyDown}
          className="flex-1 min-w-0 bg-dark-700 border border-dark-600 rounded px-1 py-0.5 text-xs text-white focus:outline-none focus:border-orange-500"
          onClick={(e) => e.stopPropagation()}
        />
      ) : (
        <span className="flex-1 min-w-0 text-xs font-medium truncate">
          {getDisplayName()}
        </span>
      )}

      {/* Unread badge */}
      {session.unreadCount > 0 && !isActive && (
        <span className="flex-shrink-0 px-1.5 py-0.5 text-[10px] font-bold bg-orange-500 text-white rounded-full">
          {session.unreadCount > 99 ? '99+' : session.unreadCount}
        </span>
      )}

      {/* Split button */}
      <button
        onClick={(e) => {
          e.stopPropagation();
          onSplit(session.id);
        }}
        className="p-0.5 rounded hover:bg-dark-600 text-dark-500 hover:text-dark-300 opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0"
        title={isSplit ? 'Remove from split' : 'Add to split view'}
      >
        <Columns className="w-3 h-3" />
      </button>

      {/* Close button */}
      <button
        onClick={(e) => {
          e.stopPropagation();
          onClose(session.id);
        }}
        className="p-0.5 rounded hover:bg-red-500/20 text-dark-500 hover:text-red-400 opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0"
        title="Close tab"
      >
        <X className="w-3 h-3" />
      </button>
    </div>
  );
});

export function TabBar() {
  const {
    sessions,
    tabOrder,
    splitSessions,
    focusedSessionId,
    createSession,
    removeSession,
    renameSession,
    setFocusedSessionId,
    markAsRead,
    reorderTabs,
    addToSplit,
    removeFromSplit,
    clearSplit,
  } = useSessionManager();

  const [dragIndex, setDragIndex] = useState(null);

  const handleDragStart = useCallback((e, index) => {
    setDragIndex(index);
    e.dataTransfer.effectAllowed = 'move';
  }, []);

  const handleDragOver = useCallback((e) => {
    e.preventDefault();
    e.dataTransfer.dropEffect = 'move';
  }, []);

  const handleDrop = useCallback((e, toIndex) => {
    e.preventDefault();
    if (dragIndex !== null && dragIndex !== toIndex) {
      reorderTabs(dragIndex, toIndex);
    }
    setDragIndex(null);
  }, [dragIndex, reorderTabs]);

  const handleFocus = useCallback((sessionId) => {
    setFocusedSessionId(sessionId);
    markAsRead(sessionId);
  }, [setFocusedSessionId, markAsRead]);

  const handleClose = useCallback((sessionId) => {
    removeSession(sessionId);
  }, [removeSession]);

  const handleSplit = useCallback((sessionId) => {
    if (splitSessions.includes(sessionId)) {
      removeFromSplit(sessionId);
    } else {
      addToSplit(sessionId);
    }
  }, [splitSessions, addToSplit, removeFromSplit]);

  const handleNewTab = useCallback(() => {
    createSession();
  }, [createSession]);

  // Get split layout info
  const getSplitInfo = () => {
    const count = splitSessions.length;
    if (count === 0) return null;
    if (count === 1) return '1 panel';
    if (count === 2) return '2 panels';
    if (count === 3) return '3 panels';
    return '2x2 grid';
  };

  return (
    <div className="flex items-center gap-1 px-2 py-1 bg-dark-900 border-b border-dark-800 overflow-x-auto">
      {/* Tabs */}
      <div className="flex items-end gap-1 flex-1 min-w-0 overflow-x-auto scrollbar-thin">
        {tabOrder.map((sessionId, index) => {
          const session = sessions[sessionId];
          if (!session) return null;

          return (
            <Tab
              key={sessionId}
              session={session}
              isActive={focusedSessionId === sessionId}
              isSplit={splitSessions.includes(sessionId)}
              index={index}
              onDragStart={handleDragStart}
              onRename={renameSession}
              onDragOver={handleDragOver}
              onDrop={handleDrop}
              onFocus={handleFocus}
              onClose={handleClose}
              onSplit={handleSplit}
            />
          );
        })}

        {/* New tab button */}
        <button
          onClick={handleNewTab}
          className="flex items-center justify-center w-8 h-8 rounded-lg hover:bg-dark-800 text-dark-500 hover:text-dark-300 transition-colors flex-shrink-0"
          title="New session (Ctrl+T)"
        >
          <Plus className="w-4 h-4" />
        </button>
      </div>

      {/* Split view controls */}
      <div className="flex items-center gap-2 flex-shrink-0 pl-2 border-l border-dark-700">
        {splitSessions.length > 0 && (
          <>
            <span className="text-xs text-dark-500">{getSplitInfo()}</span>
            <button
              onClick={clearSplit}
              className="flex items-center gap-1 px-2 py-1 rounded hover:bg-dark-800 text-dark-500 hover:text-dark-300 text-xs transition-colors"
              title="Exit split view"
            >
              <Maximize2 className="w-3 h-3" />
              <span>Single</span>
            </button>
          </>
        )}

        {splitSessions.length === 0 && tabOrder.length > 1 && (
          <button
            onClick={() => {
              // Add first two tabs to split
              if (tabOrder.length >= 2) {
                addToSplit(tabOrder[0]);
                addToSplit(tabOrder[1]);
              }
            }}
            className="flex items-center gap-1 px-2 py-1 rounded hover:bg-dark-800 text-dark-500 hover:text-dark-300 text-xs transition-colors"
            title="Split view"
          >
            <Columns className="w-3 h-3" />
            <span>Split</span>
          </button>
        )}

        {splitSessions.length >= 2 && splitSessions.length < 4 && tabOrder.length > splitSessions.length && (
          <button
            onClick={() => {
              // Find next tab not in split
              const nextTab = tabOrder.find(id => !splitSessions.includes(id));
              if (nextTab) addToSplit(nextTab);
            }}
            className="flex items-center gap-1 px-2 py-1 rounded hover:bg-dark-800 text-dark-500 hover:text-dark-300 text-xs transition-colors"
            title="Add panel"
          >
            <Grid2X2 className="w-3 h-3" />
            <span>+Panel</span>
          </button>
        )}
      </div>
    </div>
  );
}
