import {
  FolderOpen, Download, Undo2, Redo2,
  Box, Layers, Grid3X3, Maximize,
  PanelLeftClose, PanelRightClose, Menu, Settings,
} from 'lucide-react';
import { useMeshStore } from '../stores/meshStore';

export type RenderMode = 'solid' | 'flat' | 'wireframe' | 'points';

interface ExportHandlers {
  obj: () => void;
  stl: () => void;
  ply: () => void;
  off: () => void;
  glb: () => void;
}

interface ToolbarProps {
  onOpenFile: () => void;
  onExportOBJ: () => void;
  onExportSTL: () => void;
  exports?: ExportHandlers;
  onFitToView: () => void;
  onToggleLeftPanel: () => void;
  onToggleRightPanel: () => void;
  onMenuToggle?: () => void;
  isMobile?: boolean;
  selectionToolbar?: React.ReactNode;
  measureToolbar?: React.ReactNode;
  onToggleRenderSettings?: () => void;
}

const RENDER_MODES: { mode: RenderMode; label: string }[] = [
  { mode: 'solid', label: 'Solid' },
  { mode: 'flat', label: 'Flat' },
  { mode: 'wireframe', label: 'Wire' },
  { mode: 'points', label: 'Pts' },
];

const BG_OPTIONS = [
  { value: 'dark', label: 'Dark' },
  { value: 'light', label: 'Gray' },
  { value: 'white', label: 'White' },
];

const btnStyle: React.CSSProperties = {
  display: 'flex',
  alignItems: 'center',
  gap: 3,
  padding: '3px 7px',
  border: '1px solid #444',
  borderRadius: 3,
  background: '#333',
  color: '#ccc',
  cursor: 'pointer',
  fontSize: 11,
  fontFamily: 'monospace',
};

const activeBtnStyle: React.CSSProperties = {
  ...btnStyle,
  background: '#4a90d9',
  borderColor: '#4a90d9',
  color: '#fff',
};

const sepStyle: React.CSSProperties = {
  width: 1,
  height: 18,
  background: '#444',
  margin: '0 4px',
};

export function Toolbar({
  onOpenFile, onExportOBJ, onExportSTL, exports, onFitToView,
  onToggleLeftPanel, onToggleRightPanel,
  onMenuToggle, isMobile, selectionToolbar, measureToolbar, onToggleRenderSettings,
}: ToolbarProps) {
  const { state, dispatch } = useMeshStore();

  return (
    <div
      data-testid="toolbar"
      style={{
        height: 34,
        background: '#2d2d2d',
        display: 'flex',
        alignItems: 'center',
        padding: '0 6px',
        gap: 3,
        borderBottom: '1px solid #333',
        flexShrink: 0,
        flexWrap: 'nowrap',
        overflow: 'hidden',
      }}
    >
      {/* Mobile menu */}
      {isMobile && onMenuToggle && (
        <button style={btnStyle} onClick={onMenuToggle} data-testid="menu-toggle">
          <Menu size={14} />
        </button>
      )}

      {/* Panel toggles (desktop) */}
      {!isMobile && (
        <>
          <button style={btnStyle} onClick={onToggleLeftPanel} title="Toggle layers">
            <PanelLeftClose size={13} />
          </button>
          <button style={btnStyle} onClick={onToggleRightPanel} title="Toggle filters">
            <PanelRightClose size={13} />
          </button>
          <div style={sepStyle} />
        </>
      )}

      {/* File */}
      <button style={btnStyle} onClick={onOpenFile} data-testid="open-file" title="Open file (Ctrl+O)">
        <FolderOpen size={13} /> Open
      </button>
      {exports ? (
        <select
          data-testid="export-menu"
          onChange={(e) => {
            const v = e.target.value;
            if (v && exports[v as keyof ExportHandlers]) exports[v as keyof ExportHandlers]();
            e.target.value = '';
          }}
          style={{ ...btnStyle, padding: '2px 4px' }}
          defaultValue=""
        >
          <option value="" disabled>Export</option>
          <option value="obj" data-testid="export-obj">OBJ</option>
          <option value="stl" data-testid="export-stl">STL</option>
          <option value="ply" data-testid="export-ply">PLY</option>
          <option value="off" data-testid="export-off">OFF</option>
          <option value="glb" data-testid="export-glb">GLB</option>
        </select>
      ) : (
        <>
          <button style={btnStyle} onClick={onExportOBJ} data-testid="export-obj" title="Export OBJ">
            <Download size={13} /> OBJ
          </button>
          <button style={btnStyle} onClick={onExportSTL} data-testid="export-stl" title="Export STL">
            <Download size={13} /> STL
          </button>
        </>
      )}

      <div style={sepStyle} />

      {/* Undo / Redo */}
      <button
        style={btnStyle}
        onClick={() => dispatch({ type: 'UNDO' })}
        disabled={state.undoStack.length === 0}
        data-testid="undo"
        title="Undo (Ctrl+Z)"
      >
        <Undo2 size={13} />
      </button>
      <button
        style={btnStyle}
        onClick={() => dispatch({ type: 'REDO' })}
        disabled={state.redoStack.length === 0}
        data-testid="redo"
        title="Redo (Ctrl+Shift+Z)"
      >
        <Redo2 size={13} />
      </button>

      <div style={sepStyle} />

      {/* Render modes */}
      {RENDER_MODES.map(({ mode, label }) => (
        <button
          key={mode}
          style={state.globalRenderMode === mode ? activeBtnStyle : btnStyle}
          onClick={() => dispatch({ type: 'SET_RENDER_MODE', mode })}
          data-testid={`mode-${mode}`}
        >
          {label}
        </button>
      ))}

      <div style={sepStyle} />

      {/* Toggles */}
      <button
        style={state.showBBox ? activeBtnStyle : btnStyle}
        onClick={() => dispatch({ type: 'TOGGLE_BBOX' })}
        data-testid="toggle-bbox"
        title="Bounding Box (B)"
      >
        <Box size={13} />
      </button>
      <button
        style={state.showGrid ? activeBtnStyle : btnStyle}
        onClick={() => dispatch({ type: 'TOGGLE_GRID' })}
        data-testid="toggle-grid"
        title="Grid (G)"
      >
        <Grid3X3 size={13} />
      </button>

      <div style={sepStyle} />

      {/* Background */}
      <select
        value={state.bgColor}
        onChange={(e) => dispatch({ type: 'SET_BG_COLOR', color: e.target.value })}
        style={{ ...btnStyle, padding: '2px 4px' }}
        data-testid="bg-select"
      >
        {BG_OPTIONS.map((o) => (
          <option key={o.value} value={o.value}>{o.label}</option>
        ))}
      </select>

      {/* Selection tools */}
      {selectionToolbar && (
        <>
          <div style={sepStyle} />
          {selectionToolbar}
        </>
      )}

      {/* Measure tools */}
      {measureToolbar && (
        <>
          <div style={sepStyle} />
          {measureToolbar}
        </>
      )}

      <div style={{ flex: 1 }} />

      {/* Render settings */}
      {onToggleRenderSettings && (
        <button style={btnStyle} onClick={onToggleRenderSettings} data-testid="render-settings" title="Render Settings">
          <Settings size={13} />
        </button>
      )}

      {/* Fit */}
      <button style={btnStyle} onClick={onFitToView} data-testid="fit-view" title="Fit to View (Home)">
        <Maximize size={13} />
      </button>

      {/* Fullscreen */}
      <button
        style={btnStyle}
        onClick={() => {
          if (document.fullscreenElement) document.exitFullscreen();
          else document.documentElement.requestFullscreen();
        }}
        data-testid="fullscreen"
        title="Fullscreen"
      >
        <Layers size={13} />
      </button>
    </div>
  );
}
