import { memo, useState, useRef, useCallback, useEffect } from 'react';
import { X, Maximize2, GripHorizontal, GripVertical } from 'lucide-react';
import { useSessionManager } from '../contexts/SessionContext';

// Resizable divider - uses DOM manipulation during drag for smooth resize
const Divider = memo(function Divider({ direction, panelRef, onResizeEnd }) {
  const [isDragging, setIsDragging] = useState(false);
  const startPos = useRef(0);
  const startSize = useRef(0);

  const handleMouseDown = useCallback((e) => {
    e.preventDefault();

    const panel = panelRef.current;
    if (!panel) return;

    setIsDragging(true);
    startPos.current = direction === 'horizontal' ? e.clientX : e.clientY;
    startSize.current = direction === 'horizontal'
      ? panel.offsetWidth
      : panel.offsetHeight;

    // Add will-change for GPU acceleration
    panel.style.willChange = 'width, height';

    const handleMouseMove = (e) => {
      const currentPos = direction === 'horizontal' ? e.clientX : e.clientY;
      const delta = currentPos - startPos.current;
      const newSize = startSize.current + delta;

      // Get parent size for percentage calculation
      const parent = panel.parentElement;
      const parentSize = direction === 'horizontal'
        ? parent.offsetWidth
        : parent.offsetHeight;

      // Clamp between 20% and 80%
      const minSize = parentSize * 0.2;
      const maxSize = parentSize * 0.8;
      const clampedSize = Math.max(minSize, Math.min(maxSize, newSize));

      // Direct DOM manipulation - no React re-render
      if (direction === 'horizontal') {
        panel.style.width = `${clampedSize}px`;
      } else {
        panel.style.height = `${clampedSize}px`;
      }
    };

    const handleMouseUp = (e) => {
      setIsDragging(false);
      panel.style.willChange = 'auto';

      // Calculate final percentage and update React state
      const parent = panel.parentElement;
      const parentSize = direction === 'horizontal'
        ? parent.offsetWidth
        : parent.offsetHeight;
      const currentSize = direction === 'horizontal'
        ? panel.offsetWidth
        : panel.offsetHeight;
      const percentage = (currentSize / parentSize) * 100;

      // Clear inline style and let React take over
      if (direction === 'horizontal') {
        panel.style.width = '';
      } else {
        panel.style.height = '';
      }

      onResizeEnd(percentage);

      document.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('mouseup', handleMouseUp);
    };

    document.addEventListener('mousemove', handleMouseMove);
    document.addEventListener('mouseup', handleMouseUp);
  }, [direction, panelRef, onResizeEnd]);

  return (
    <div
      onMouseDown={handleMouseDown}
      className={`
        flex items-center justify-center bg-dark-800 hover:bg-dark-700 transition-colors flex-shrink-0
        ${direction === 'horizontal' ? 'w-2 cursor-col-resize' : 'h-2 cursor-row-resize'}
        ${isDragging ? 'bg-orange-500' : ''}
      `}
    >
      {direction === 'horizontal' ? (
        <GripVertical className="w-3 h-3 text-dark-600" />
      ) : (
        <GripHorizontal className="w-3 h-3 text-dark-600" />
      )}
    </div>
  );
});

// Panel wrapper with header
const PanelWrapper = memo(function PanelWrapper({ sessionId, children, onRemove, onMaximize }) {
  const { sessions, setFocusedSessionId, focusedSessionId } = useSessionManager();
  const session = sessions[sessionId];
  const isFocused = focusedSessionId === sessionId;

  if (!session) return null;

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

  // Get display name
  const getDisplayName = () => {
    if (session.name) return session.name;
    const hostName = session.host.charAt(0).toUpperCase() + session.host.slice(1);
    const context = session.currentContext || session.project.split('/').pop() || 'New';
    return `${hostName}: ${context}`;
  };

  return (
    <div
      className={`
        flex flex-col h-full overflow-hidden rounded-lg border
        ${isFocused ? 'border-orange-500/50' : 'border-dark-700'}
      `}
      onClick={() => setFocusedSessionId(sessionId)}
    >
      {/* Mini header */}
      <div
        className="flex items-center gap-2 px-2 py-1 bg-dark-800/80 border-b border-dark-700 flex-shrink-0"
        style={{ borderLeftColor: getHostColor(), borderLeftWidth: '3px' }}
      >
        <span className={`w-2 h-2 rounded-full ${session.active ? 'bg-green-500' : 'bg-dark-500'}`} />
        <span className="flex-1 text-xs font-medium text-dark-300 truncate">
          {getDisplayName()}
        </span>
        {session.isProcessing && (
          <span className="text-[10px] text-orange-400 animate-pulse">Processing...</span>
        )}
        <button
          onClick={(e) => {
            e.stopPropagation();
            onMaximize(sessionId);
          }}
          className="p-0.5 rounded hover:bg-dark-600 text-dark-500 hover:text-dark-300"
          title="Maximize"
        >
          <Maximize2 className="w-3 h-3" />
        </button>
        <button
          onClick={(e) => {
            e.stopPropagation();
            onRemove(sessionId);
          }}
          className="p-0.5 rounded hover:bg-red-500/20 text-dark-500 hover:text-red-400"
          title="Remove from split"
        >
          <X className="w-3 h-3" />
        </button>
      </div>

      {/* Content */}
      <div className="flex-1 min-h-0 overflow-hidden">
        {children}
      </div>
    </div>
  );
});

export function SplitLayout({ splitSessions, renderPanel }) {
  const { removeFromSplit, clearSplit, setFocusedSessionId } = useSessionManager();
  const [sizes, setSizes] = useState({ h: 50, v: 50 });

  // Refs for direct DOM manipulation during resize
  const leftPanelRef = useRef(null);
  const topPanelRef = useRef(null);

  const handleRemove = useCallback((sessionId) => {
    removeFromSplit(sessionId);
  }, [removeFromSplit]);

  const handleMaximize = useCallback((sessionId) => {
    clearSplit();
    setFocusedSessionId(sessionId);
  }, [clearSplit, setFocusedSessionId]);

  const handleHorizontalResizeEnd = useCallback((percentage) => {
    setSizes(prev => ({ ...prev, h: percentage }));
  }, []);

  const handleVerticalResizeEnd = useCallback((percentage) => {
    setSizes(prev => ({ ...prev, v: percentage }));
  }, []);

  const count = splitSessions.length;

  if (count === 0) return null;

  // Single panel (shouldn't happen in split mode, but handle it)
  if (count === 1) {
    return (
      <div className="h-full p-1">
        <PanelWrapper
          sessionId={splitSessions[0]}
          onRemove={handleRemove}
          onMaximize={handleMaximize}
        >
          {renderPanel(splitSessions[0])}
        </PanelWrapper>
      </div>
    );
  }

  // Two panels - horizontal split
  if (count === 2) {
    return (
      <div className="h-full flex p-1 gap-0">
        <div
          ref={leftPanelRef}
          style={{ width: `${sizes.h}%` }}
          className="min-w-0 h-full"
        >
          <PanelWrapper
            sessionId={splitSessions[0]}
            onRemove={handleRemove}
            onMaximize={handleMaximize}
          >
            {renderPanel(splitSessions[0])}
          </PanelWrapper>
        </div>
        <Divider
          direction="horizontal"
          panelRef={leftPanelRef}
          onResizeEnd={handleHorizontalResizeEnd}
        />
        <div style={{ flex: 1 }} className="min-w-0 h-full">
          <PanelWrapper
            sessionId={splitSessions[1]}
            onRemove={handleRemove}
            onMaximize={handleMaximize}
          >
            {renderPanel(splitSessions[1])}
          </PanelWrapper>
        </div>
      </div>
    );
  }

  // Three panels - 2 on left, 1 on right
  if (count === 3) {
    return (
      <div className="h-full flex p-1 gap-0">
        {/* Left column - 2 panels stacked */}
        <div
          ref={leftPanelRef}
          style={{ width: `${sizes.h}%` }}
          className="flex flex-col min-w-0"
        >
          <div
            ref={topPanelRef}
            style={{ height: `${sizes.v}%` }}
            className="min-h-0"
          >
            <PanelWrapper
              sessionId={splitSessions[0]}
              onRemove={handleRemove}
              onMaximize={handleMaximize}
            >
              {renderPanel(splitSessions[0])}
            </PanelWrapper>
          </div>
          <Divider
            direction="vertical"
            panelRef={topPanelRef}
            onResizeEnd={handleVerticalResizeEnd}
          />
          <div style={{ flex: 1 }} className="min-h-0">
            <PanelWrapper
              sessionId={splitSessions[1]}
              onRemove={handleRemove}
              onMaximize={handleMaximize}
            >
              {renderPanel(splitSessions[1])}
            </PanelWrapper>
          </div>
        </div>

        <Divider
          direction="horizontal"
          panelRef={leftPanelRef}
          onResizeEnd={handleHorizontalResizeEnd}
        />

        {/* Right column - 1 panel full height */}
        <div style={{ flex: 1 }} className="min-w-0">
          <PanelWrapper
            sessionId={splitSessions[2]}
            onRemove={handleRemove}
            onMaximize={handleMaximize}
          >
            {renderPanel(splitSessions[2])}
          </PanelWrapper>
        </div>
      </div>
    );
  }

  // Four panels - 2x2 grid
  if (count >= 4) {
    return (
      <div className="h-full flex flex-col p-1 gap-0">
        {/* Top row */}
        <div
          ref={topPanelRef}
          style={{ height: `${sizes.v}%` }}
          className="flex min-h-0"
        >
          <div
            ref={leftPanelRef}
            style={{ width: `${sizes.h}%` }}
            className="min-w-0 h-full"
          >
            <PanelWrapper
              sessionId={splitSessions[0]}
              onRemove={handleRemove}
              onMaximize={handleMaximize}
            >
              {renderPanel(splitSessions[0])}
            </PanelWrapper>
          </div>
          <Divider
            direction="horizontal"
            panelRef={leftPanelRef}
            onResizeEnd={handleHorizontalResizeEnd}
          />
          <div style={{ flex: 1 }} className="min-w-0 h-full">
            <PanelWrapper
              sessionId={splitSessions[1]}
              onRemove={handleRemove}
              onMaximize={handleMaximize}
            >
              {renderPanel(splitSessions[1])}
            </PanelWrapper>
          </div>
        </div>

        <Divider
          direction="vertical"
          panelRef={topPanelRef}
          onResizeEnd={handleVerticalResizeEnd}
        />

        {/* Bottom row */}
        <div style={{ flex: 1 }} className="flex min-h-0">
          <div style={{ width: `${sizes.h}%` }} className="min-w-0 h-full">
            <PanelWrapper
              sessionId={splitSessions[2]}
              onRemove={handleRemove}
              onMaximize={handleMaximize}
            >
              {renderPanel(splitSessions[2])}
            </PanelWrapper>
          </div>
          <Divider
            direction="horizontal"
            panelRef={leftPanelRef}
            onResizeEnd={handleHorizontalResizeEnd}
          />
          <div style={{ flex: 1 }} className="min-w-0 h-full">
            <PanelWrapper
              sessionId={splitSessions[3]}
              onRemove={handleRemove}
              onMaximize={handleMaximize}
            >
              {renderPanel(splitSessions[3])}
            </PanelWrapper>
          </div>
        </div>
      </div>
    );
  }

  return null;
}
