import React from "react";
import { TerminalComponent, type TerminalRef } from "./terminal";
import { TerminalSessionTabs, type TerminalSessionInfo } from "./terminal-session-tabs";
import { Icon } from "../../icon";
import { SpecialKeysStrip } from "./special-keys-strip";
import { SpecialKeysPanel } from "./special-keys-panel";
import type { ModifierKey } from "../../../hooks/use-special-keys";
import type { TerminalSession } from "../../../api/terminal";

interface Props {
  instanceId: string;
  sessions: TerminalSession[];
  sessionInfos: TerminalSessionInfo[];
  activeSessionId: string;
  terminalRefs: React.MutableRefObject<Record<string, React.RefObject<TerminalRef>>>;
  status: string;
  error: string | null;
  loading: boolean;
  isKeyboardOpen: boolean;
  keyboardHeight: number;
  isVisible: boolean;
  activeModifier: ModifierKey | null;
  showSpecialKeysPanel: boolean;
  onToggleHeader: () => void;
  onNavigateBack: () => void;
  onFontSizeChange: (delta: number) => void;
  onSelect: (id: string) => void;
  onClose: (id: string) => void;
  onCreate: () => void;
  onRename: (id: string, name: string) => void;
  onTerminalReady: (
    sendData: (data: string) => void,
    status: "connecting" | "connected" | "disconnected" | "error" | "resetting",
    focusInput: () => void,
    changeFontSize: (delta: number) => void,
  ) => void;
  onSendKey: (data: string) => void;
  onModifierChange: (mod: ModifierKey | null) => void;
  onShowSpecialKeys: () => void;
  onHideSpecialKeys: () => void;
  onKeepFocus: () => void;
}

export const MobileTerminalView: React.FC<Props> = ({
  instanceId,
  sessions,
  sessionInfos,
  activeSessionId,
  terminalRefs,
  status,
  error,
  loading,
  isKeyboardOpen,
  keyboardHeight,
  isVisible,
  activeModifier,
  showSpecialKeysPanel,
  onToggleHeader,
  onNavigateBack,
  onFontSizeChange,
  onSelect,
  onClose,
  onCreate,
  onRename,
  onTerminalReady,
  onSendKey,
  onModifierChange,
  onShowSpecialKeys,
  onHideSpecialKeys,
  onKeepFocus,
}) => {
  const activeSession = sessions.find((s) => s.id === activeSessionId);

  return (
    <section className="terminal-page mobile">
      <div className={`mobile-terminal-overlay ${isVisible ? "visible" : "hidden"}`} onClick={(e) => e.stopPropagation()}>
        <div className="mobile-terminal-toolbar">
          <div className="mobile-terminal-toolbar-left">
            <button className="mobile-terminal-toolbtn" onClick={onNavigateBack} type="button" aria-label="Back">
              <Icon name="arrow-left" size="sm" />
            </button>
          </div>
          <div className="mobile-terminal-toolbar-center">
            <span className="mobile-terminal-title">{activeSession?.name || "Terminal"}</span>
            <span className={`mobile-terminal-status status-dot ${status}`} aria-label={`Connection status: ${status}`} />
          </div>
          <div className="mobile-terminal-toolbar-right">
            <button className="mobile-terminal-toolbtn" onClick={() => onFontSizeChange(-1)} type="button" aria-label="Decrease font size">
              <span style={{ fontSize: "0.75rem" }}>A-</span>
            </button>
            <button className="mobile-terminal-toolbtn" onClick={() => onFontSizeChange(1)} type="button" aria-label="Increase font size">
              <span style={{ fontSize: "1rem" }}>A+</span>
            </button>
            <button className="mobile-terminal-toolbtn" onClick={onNavigateBack} type="button" aria-label="Exit terminal">
              <Icon name="close" size="sm" />
            </button>
          </div>
        </div>
        <div className="mobile-terminal-overlay-tabs">
          <TerminalSessionTabs
            sessions={sessionInfos}
            activeSessionId={activeSessionId}
            onSelect={onSelect}
            onClose={onClose}
            onCreate={onCreate}
            onRename={onRename}
            isMobile={true}
          />
        </div>
      </div>

      <div
        className="terminal-page-content mobile-full"
        style={{ paddingBottom: isKeyboardOpen ? keyboardHeight : 0 }}
        onClick={onToggleHeader}
      >
        {error && <div className="terminal-error-banner">{error}</div>}
        {sessions
          .filter((session) => session.id === activeSessionId)
          .map((session) => (
            <div key={session.id} className="terminal-instance active">
              <TerminalComponent
                ref={terminalRefs.current[session.id]}
                instanceId={instanceId}
                sessionId={session.id}
                onClose={() => onClose(session.id)}
                isMobile={true}
                showControls={false}
                activeModifier={activeModifier}
                onModifierChange={onModifierChange}
                onTerminalReady={onTerminalReady}
              />
            </div>
          ))}
        {sessions.length === 0 && !loading && (
          <div className="terminal-empty-state">
            <p>No terminal sessions. Press Alt+Shift+N to create one.</p>
          </div>
        )}
      </div>

      <SpecialKeysStrip
        onSend={onSendKey}
        isVisible={!showSpecialKeysPanel}
        onMoreClick={onShowSpecialKeys}
        onKeepFocus={onKeepFocus}
        activeModifier={activeModifier}
        onModifierChange={onModifierChange}
      />

      <SpecialKeysPanel
        onSend={onSendKey}
        isOpen={showSpecialKeysPanel}
        onClose={onHideSpecialKeys}
        onKeepFocus={onKeepFocus}
        activeModifier={activeModifier}
        onModifierChange={onModifierChange}
      />
    </section>
  );
};
