
import React from 'react';
import { Trash2, PlusCircle, Power, Zap, Gauge, Move } from 'lucide-react';
import { IOLogicRule, LogicCondition, LogicAction, LogicTriggerType, LogicActionType, AxisData } from '../types';

interface LadderEditorProps {
  logicRules: IOLogicRule[];
  inputNames: string[];
  outputNames: string[];
  currentInputs: boolean[];
  currentOutputs: boolean[];
  onAddRule: (rule: IOLogicRule) => void;
  onDeleteRule: (id: string) => void;
  onUpdateRule: (id: string, updates: Partial<IOLogicRule>) => void;
  axes: AxisData[];
}

export const LadderEditor: React.FC<LadderEditorProps> = ({
  logicRules,
  inputNames,
  outputNames,
  currentInputs,
  currentOutputs,
  onAddRule,
  onDeleteRule,
  onUpdateRule,
  axes
}) => {
  return (
    <div className="flex-1 bg-gray-950 flex flex-col relative overflow-hidden">
      {/* Background Grid Pattern */}
      <div className="absolute inset-0 opacity-[0.03] pointer-events-none"
        style={{ backgroundImage: 'radial-gradient(#fff 1px, transparent 1px)', backgroundSize: '24px 24px' }} />

      {/* Toolbar */}
      <div className="h-12 border-b border-gray-800 flex items-center px-6 justify-between shrink-0 bg-gray-900/50 backdrop-blur-md">
        <h3 className="text-xs font-black uppercase tracking-widest text-gray-400">Main Controller (Ladder Logic)</h3>
        <button
          onClick={() => onAddRule({
            id: crypto.randomUUID(),
            enabled: true,
            triggerType: LogicTriggerType.INPUT_BIT,
            inputPort: 0,
            triggerAxisIndex: 0,
            triggerCompareOp: LogicCondition.GREATER,
            triggerValue: 0,
            actionType: LogicActionType.OUTPUT_COIL,
            outputPort: 0,
            action: LogicAction.SET_ON,
            targetAxisIndex: 0,
            targetAxisValue: 0
          })}
          className="flex items-center gap-2 bg-blue-600 hover:bg-blue-500 text-white px-4 py-1.5 rounded-full text-xs font-bold transition-all transform active:scale-95"
        >
          <PlusCircle size={14} /> Add New Rung
        </button>
      </div>

      {/* Programming Workspace */}
      <div className="flex-1 overflow-y-auto p-12 custom-scrollbar relative flex flex-col items-center">
        {/* Left Bus Bar (Hot) */}
        <div className="absolute left-10 top-0 bottom-0 w-1 bg-gradient-to-b from-red-600 via-red-500 to-red-600 shadow-[0_0_10px_rgba(239,68,68,0.5)] z-10" />
        {/* Right Bus Bar (Neutral) */}
        <div className="absolute right-10 top-0 bottom-0 w-1 bg-gradient-to-b from-blue-600 via-blue-500 to-blue-600 shadow-[0_0_10px_rgba(59,130,246,0.5)] z-10" />

        <div className="w-full max-w-4xl space-y-12">
          {logicRules.map((rule, index) => {
            const isInputTrigger = rule.triggerType === LogicTriggerType.INPUT_BIT;
            const isAxisTrigger = rule.triggerType === LogicTriggerType.AXIS_COMPARE;
            const isOutputAction = rule.actionType === LogicActionType.OUTPUT_COIL;
            const isAxisAction = rule.actionType === LogicActionType.AXIS_MOVE;

            const inputActive = isInputTrigger && currentInputs[rule.inputPort];
            const outputActive = isOutputAction && currentOutputs[rule.outputPort];

            return (
              <div key={rule.id} className="relative flex items-center group mb-4 p-4 rounded-xl border border-gray-800 bg-gray-900/30 hover:bg-gray-900/50 transition-colors">
                {/* Rung Number */}
                <div className="absolute -left-8 text-[10px] font-mono text-gray-600">{(index + 1).toString().padStart(3, '0')}</div>

                {/* Delete Button */}
                <button
                  onClick={() => onDeleteRule(rule.id)}
                  className="absolute -right-8 p-2 text-gray-700 hover:text-red-500 transition-colors opacity-0 group-hover:opacity-100"
                >
                  <Trash2 size={16} />
                </button>

                <div className="flex-1 flex items-center gap-6">

                  {/* LEFT: TRIGGER */}
                  <div className="flex-1 flex flex-col gap-2">
                    <div className="flex items-center gap-2 mb-1">
                      <button
                        onClick={() => onUpdateRule(rule.id, { triggerType: LogicTriggerType.INPUT_BIT })}
                        className={`flex items-center gap-1 text-[10px] uppercase font-bold px-2 py-0.5 rounded border ${isInputTrigger ? 'bg-green-500/10 border-green-500 text-green-500' : 'border-transparent text-gray-600 hover:bg-gray-800'}`}
                      >
                        <Zap size={10} /> IO Input
                      </button>
                      <button
                        onClick={() => onUpdateRule(rule.id, { triggerType: LogicTriggerType.AXIS_COMPARE })}
                        className={`flex items-center gap-1 text-[10px] uppercase font-bold px-2 py-0.5 rounded border ${isAxisTrigger ? 'bg-blue-500/10 border-blue-500 text-blue-500' : 'border-transparent text-gray-600 hover:bg-gray-800'}`}
                      >
                        <Gauge size={10} /> Axis Logic
                      </button>
                    </div>

                    <div className="h-16 bg-gray-950 border border-gray-800 rounded-lg flex items-center justify-center relative p-2">
                      {isInputTrigger ? (
                        <div className="flex flex-col items-center">
                          <span className="text-[10px] text-gray-500 mb-1">{inputNames[rule.inputPort] || `Input ${rule.inputPort}`}</span>
                          <div className={`relative w-8 h-8 flex items-center justify-center border-2 rounded ${inputActive ? 'border-green-500 bg-green-500/20' : 'border-gray-700'}`}>
                            <select
                              className="bg-transparent text-xs font-bold text-center w-full h-full outline-none appearance-none cursor-pointer text-white"
                              value={rule.inputPort}
                              onChange={(e) => onUpdateRule(rule.id, { inputPort: parseInt(e.target.value) })}
                            >
                              {Array.from({ length: 32 }).map((_, i) => <option key={i} value={i} className="bg-gray-900 border-none">X{i}</option>)}
                            </select>
                          </div>
                        </div>
                      ) : (
                        <div className="flex items-center gap-2 w-full">
                          <select
                            className="bg-gray-900 border border-gray-700 rounded text-[10px] text-white px-2 py-1 w-20 outline-none"
                            value={rule.triggerAxisIndex}
                            onChange={(e) => onUpdateRule(rule.id, { triggerAxisIndex: parseInt(e.target.value) })}
                          >
                            {axes.map(a => <option key={a.id} value={a.id}>CH{a.id}</option>)}
                          </select>
                          <select
                            className="bg-gray-900 border border-gray-700 rounded text-[10px] text-white px-1 py-1 w-12 text-center outline-none"
                            value={rule.triggerCompareOp}
                            onChange={(e) => onUpdateRule(rule.id, { triggerCompareOp: e.target.value as LogicCondition })}
                          >
                            <option value={LogicCondition.GREATER}>&gt;</option>
                            <option value={LogicCondition.LESS}>&lt;</option>
                            <option value={LogicCondition.EQUAL}>=</option>
                          </select>
                          <input
                            type="number"
                            className="bg-gray-900 border border-gray-700 rounded text-[10px] text-white px-2 py-1 w-16 outline-none"
                            value={rule.triggerValue}
                            onChange={(e) => onUpdateRule(rule.id, { triggerValue: parseFloat(e.target.value) })}
                          />
                        </div>
                      )}
                    </div>
                  </div>

                  {/* ARROW */}
                  <div className="text-gray-700">➡</div>

                  {/* RIGHT: ACTION */}
                  <div className="flex-1 flex flex-col gap-2">
                    <div className="flex items-center gap-2 mb-1 justify-end">
                      <button
                        onClick={() => onUpdateRule(rule.id, { actionType: LogicActionType.OUTPUT_COIL })}
                        className={`flex items-center gap-1 text-[10px] uppercase font-bold px-2 py-0.5 rounded border ${isOutputAction ? 'bg-red-500/10 border-red-500 text-red-500' : 'border-transparent text-gray-600 hover:bg-gray-800'}`}
                      >
                        <Zap size={10} /> Output
                      </button>
                      <button
                        onClick={() => onUpdateRule(rule.id, { actionType: LogicActionType.AXIS_MOVE })}
                        className={`flex items-center gap-1 text-[10px] uppercase font-bold px-2 py-0.5 rounded border ${isAxisAction ? 'bg-blue-500/10 border-blue-500 text-blue-500' : 'border-transparent text-gray-600 hover:bg-gray-800'}`}
                      >
                        <Move size={10} /> Move Axis
                      </button>
                    </div>

                    <div className="h-16 bg-gray-950 border border-gray-800 rounded-lg flex items-center justify-center relative p-2">
                      {isOutputAction ? (
                        <div className="flex flex-col items-center">
                          <span className="text-[10px] text-gray-500 mb-1">{outputNames[rule.outputPort] || `Output ${rule.outputPort}`}</span>
                          <div className={`relative w-8 h-8 flex items-center justify-center rounded-full border-2 ${outputActive ? 'border-red-500 bg-red-500/20 shadow-[0_0_10px_#ef4444]' : 'border-gray-700'}`}>
                            <select
                              className="bg-transparent text-xs font-bold text-center w-full h-full outline-none appearance-none cursor-pointer text-white"
                              value={rule.outputPort}
                              onChange={(e) => onUpdateRule(rule.id, { outputPort: parseInt(e.target.value) })}
                            >
                              {Array.from({ length: 32 }).map((_, i) => <option key={i} value={i} className="bg-gray-900 border-none">Y{i}</option>)}
                            </select>
                          </div>
                        </div>
                      ) : (
                        <div className="flex items-center gap-2 w-full">
                          <span className="text-[9px] text-gray-500 font-bold">MOVE</span>
                          <select
                            className="bg-gray-900 border border-gray-700 rounded text-[10px] text-white px-2 py-1 w-20 outline-none"
                            value={rule.targetAxisIndex}
                            onChange={(e) => onUpdateRule(rule.id, { targetAxisIndex: parseInt(e.target.value) })}
                          >
                            {axes.map(a => <option key={a.id} value={a.id}>CH{a.id}</option>)}
                          </select>
                          <span className="text-[9px] text-gray-500 font-bold">TO</span>
                          <input
                            type="number"
                            className="bg-gray-900 border border-gray-700 rounded text-[10px] text-white px-2 py-1 w-16 outline-none"
                            placeholder="Pos"
                            value={rule.targetAxisValue}
                            onChange={(e) => onUpdateRule(rule.id, { targetAxisValue: parseFloat(e.target.value) })}
                          />
                        </div>
                      )}
                    </div>
                  </div>

                </div>
              </div>
            );
          })}

          {/* End of Program */}
          <div className="flex items-center justify-center py-10 opacity-20 select-none">
            <div className="h-[2px] w-20 bg-gray-600" />
            <span className="mx-4 text-xs font-black tracking-widest uppercase">End of Program</span>
            <div className="h-[2px] w-20 bg-gray-600" />
          </div>
        </div>
      </div>
    </div>
  );
};
