
import React from 'react';
import { ArrowUp, ArrowDown, RotateCcw, RotateCw, StopCircle, Disc, ChevronsUp, ChevronsDown, Magnet, AlertTriangle } from 'lucide-react';
import { AgvState, AgvMotionState, AgvRunConfig } from '../types';

interface AgvManualControlsProps {
  agvState: AgvState;
  setMotion: (state: AgvMotionState) => void;
  setRunConfig: (config: AgvRunConfig) => void;
  setError: (error: string | null) => void;
  onTurn180: (direction: 'LEFT' | 'RIGHT') => void;
  setLiftStatus: (status: 'IDLE' | 'UP' | 'DOWN') => void;
  setMagnet: (isOn: boolean) => void;
}

const AgvManualControls: React.FC<AgvManualControlsProps> = ({
  agvState,
  setMotion,
  setRunConfig,
  setError,
  onTurn180,
  setLiftStatus,
  setMagnet,
}) => {
  const isRunning = agvState.motionState === AgvMotionState.RUNNING || agvState.motionState === AgvMotionState.MARK_STOPPING;
  const isError = agvState.error !== null;

  const updateRunConfig = (key: keyof AgvRunConfig, value: any) => {
    if (isError) return;
    setRunConfig({
      ...agvState.runConfig,
      [key]: value
    });
  };

  const handleMarkStop = () => {
    if (agvState.motionState === AgvMotionState.RUNNING) {
      setRunConfig({
        ...agvState.runConfig,
        speedLevel: 'L'
      });
      setMotion(AgvMotionState.MARK_STOPPING);
    }
  };

  const resetError = () => {
    setError(null);
  };
  const setManualMotion = (motion: AgvMotionState, direction?: 'FWD' | 'BWD') => {
    setMotion(motion);
    if (direction) {
      updateRunConfig('direction', direction);
    }
  };

  return (

    <div className="flex flex-col gap-4 p-3 bg-gray-900 border-b border-gray-700">

      {/* Error Overlay */}
      {isError && (
        <div className="bg-red-900/80 border border-red-600 p-3 rounded text-center animate-pulse">
          <div className="text-red-100 font-bold text-sm flex items-center justify-center gap-2 mb-2">
            <AlertTriangle size={18} />
            {agvState.error}
          </div>
          <button onClick={resetError} className="bg-red-600 hover:bg-red-500 text-white text-xs font-bold px-3 py-1 rounded shadow-sm">
            RESET ERROR
          </button>
        </div>
      )}

      <div className={`${isError ? 'opacity-50 pointer-events-none' : ''}`}>
        <div className="flex justify-between items-center mb-2 px-1">
          <h3 className="text-xs font-bold text-gray-400 uppercase tracking-wider">Manual Operation</h3>
        </div>

        <div className="bg-gray-800 rounded-lg p-3 border border-gray-700 shadow-inner">
          <div className="grid grid-cols-3 gap-2 mb-3">
            <button
              onClick={() => setLiftStatus('UP')}
              disabled={agvState.liftHeight === 100}
              className={`h-10 rounded flex items-center justify-center transition-colors shadow ${agvState.liftStatus === 'UP'
                ? 'bg-blue-600 text-white'
                : 'bg-gray-700 hover:bg-gray-600 text-gray-300'
                }`}
            >
              <ChevronsUp size={20} />
            </button>
            <button
              disabled={isRunning}
              onMouseDown={() => setManualMotion(AgvMotionState.FORWARD, 'FWD')}
              onMouseUp={() => setManualMotion(AgvMotionState.IDLE)}
              className="h-10 bg-gray-700 hover:bg-gray-600 rounded flex items-center justify-center active:bg-blue-600 disabled:opacity-30 transition-colors shadow"
            >
              <ArrowUp size={24} />
            </button>
            <button
              onClick={() => setMagnet(true)}
              disabled={agvState.magnetOn}
              className={`h-10 rounded flex items-center justify-center transition-colors shadow ${agvState.magnetOn
                ? 'bg-orange-600 text-white opacity-50 cursor-not-allowed'
                : 'bg-gray-700 hover:bg-gray-600 text-gray-300'
                }`}
            >
              <Magnet size={20} />
            </button>

            <button
              disabled={isRunning}
              onMouseDown={() => setManualMotion(AgvMotionState.TURN_LEFT)}
              onMouseUp={() => setManualMotion(AgvMotionState.IDLE)}
              className="h-10 bg-gray-700 hover:bg-gray-600 rounded flex items-center justify-center active:bg-blue-600 disabled:opacity-30 transition-colors shadow"
            >
              <RotateCcw size={20} />
            </button>
            <button
              onClick={() => setManualMotion(AgvMotionState.IDLE)}
              className="h-10 bg-red-800 hover:bg-red-700 rounded flex items-center justify-center text-white shadow"
            >
              <StopCircle size={24} />
            </button>
            <button
              disabled={isRunning}
              onMouseDown={() => setManualMotion(AgvMotionState.TURN_RIGHT)}
              onMouseUp={() => setManualMotion(AgvMotionState.IDLE)}
              className="h-10 bg-gray-700 hover:bg-gray-600 rounded flex items-center justify-center active:bg-blue-600 disabled:opacity-30 transition-colors shadow"
            >
              <RotateCw size={20} />
            </button>

            <button
              onClick={() => setLiftStatus('DOWN')}
              disabled={agvState.liftHeight === 0}
              className={`h-10 rounded flex items-center justify-center transition-colors shadow ${agvState.liftStatus === 'DOWN'
                ? 'bg-blue-600 text-white'
                : 'bg-gray-700 hover:bg-gray-600 text-gray-300'
                }`}
            >
              <ChevronsDown size={20} />
            </button>
            <button
              disabled={isRunning}
              onMouseDown={() => setManualMotion(AgvMotionState.BACKWARD, 'BWD')}
              onMouseUp={() => setManualMotion(AgvMotionState.IDLE)}
              className="h-10 bg-gray-700 hover:bg-gray-600 rounded flex items-center justify-center active:bg-blue-600 disabled:opacity-30 transition-colors shadow"
            >
              <ArrowDown size={24} />
            </button>
            <button
              onClick={() => setMagnet(false)}
              disabled={!agvState.magnetOn}
              className={`h-10 rounded flex items-center justify-center transition-colors shadow relative ${!agvState.magnetOn
                ? 'bg-gray-600 text-gray-500 cursor-not-allowed opacity-50'
                : 'bg-gray-700 hover:bg-gray-600 text-gray-300'
                }`}
            >
              <Magnet size={20} />
              <div className="absolute inset-0 flex items-center justify-center pointer-events-none">
                <div className="w-6 h-0.5 bg-red-500 rotate-45 transform origin-center"></div>
              </div>
            </button>
          </div>

          {/* Extra Actions */}
          <div className="grid grid-cols-2 gap-2">
            <button
              disabled={isRunning}
              onClick={() => onTurn180('LEFT')}
              className="text-xs py-1.5 bg-gray-700 rounded hover:bg-gray-600 flex items-center justify-center gap-1 disabled:opacity-30 shadow-sm"
            >
              <RotateCcw size={12} /> L-Turn 180
            </button>
            <button
              disabled={isRunning}
              onClick={() => onTurn180('RIGHT')}
              className="text-xs py-1.5 bg-gray-700 rounded hover:bg-gray-600 flex items-center justify-center gap-1 disabled:opacity-30 shadow-sm"
            >
              <RotateCw size={12} /> R-Turn 180
            </button>
            <button
              disabled={!isRunning || agvState.motionState === AgvMotionState.MARK_STOPPING}
              onClick={handleMarkStop}
              className={`col-span-2 text-xs py-1.5 border rounded flex items-center justify-center gap-1 shadow-sm transition-colors disabled:opacity-30 ${agvState.motionState === AgvMotionState.MARK_STOPPING
                ? 'bg-yellow-600 text-black border-yellow-500 font-bold'
                : 'bg-yellow-900/50 text-yellow-200 border-yellow-800/50 hover:bg-yellow-900/70'
                }`}
            >
              <Disc size={12} /> {agvState.motionState === AgvMotionState.MARK_STOPPING ? 'Stopping at Mark...' : 'Drive to Next Mark'}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default AgvManualControls;
