
import React, { useState } from 'react';
import {
  Trash2,
  Settings, Link as LinkIcon, Move, RotateCw, Power,
  Download, Upload, Box
} from 'lucide-react';
import {
  SimObject, ObjectType, AxisObject,
  CylinderObject, LedObject, SwitchObject, AxisData
} from '../types';

interface SidebarProps {
  objects: SimObject[];
  selectedId: string | null;
  isPlaying: boolean;
  inputNames: string[];
  outputNames: string[];
  axes: AxisData[];
  onAddObject: (type: ObjectType) => void;
  onDeleteObject: (id: string) => void;
  onUpdateObject: (id: string, updates: Partial<SimObject>) => void;
  onUpdateAxis: (index: number, updates: Partial<AxisData>) => void;
  onSelect: React.Dispatch<React.SetStateAction<string | null>>;
  onUpdatePortName: (type: 'input' | 'output', index: number, name: string) => void;
}

export const Sidebar: React.FC<SidebarProps> = ({
  objects,
  selectedId,
  isPlaying,
  inputNames,
  outputNames,
  axes,
  onAddObject,
  onDeleteObject,
  onUpdateObject,
  onUpdateAxis,
  onSelect,
  onUpdatePortName,
}) => {
  const selectedObject = objects.find(o => o.id === selectedId);

  const renderInput = (label: string, value: any, onChange: (val: any) => void, type = "text", step?: number) => (
    <div className="mb-3">
      <label className="block text-[10px] text-gray-500 mb-1 font-bold uppercase tracking-wider">{label}</label>
      <input
        type={type}
        step={step}
        className="w-full bg-gray-950 border border-gray-800 rounded px-2 py-1.5 text-sm text-white focus:outline-none focus:border-blue-500 transition-colors"
        value={value}
        onChange={(e) => {
          const val = type === 'number' ? parseFloat(e.target.value) : e.target.value;
          onChange(val);
        }}
      />
    </div>
  );

  return (
    <div className="w-80 bg-gray-900 border-l border-gray-800 flex flex-col h-full overflow-hidden select-none shadow-xl shrink-0">

      {/* Header */}
      <div className="p-4 border-b border-gray-800 bg-gray-950/50 flex items-center justify-between">
        <h2 className="text-xs font-black uppercase tracking-widest text-gray-400">Layout Config</h2>
      </div>

      {/* Tool Box */}
      <div className="p-4 grid grid-cols-3 gap-2 border-b border-gray-800 bg-gray-950/20">
        <ToolBtn icon={<Move size={16} />} label="Lin Axis" onClick={() => onAddObject(ObjectType.AXIS_LINEAR)} />
        <ToolBtn icon={<RotateCw size={16} />} label="Rot Axis" onClick={() => onAddObject(ObjectType.AXIS_ROTARY)} />
        <ToolBtn icon={<LinkIcon size={16} />} label="Cylinder" onClick={() => onAddObject(ObjectType.CYLINDER)} />
        <ToolBtn icon={<Power size={16} />} label="Switch" onClick={() => onAddObject(ObjectType.SWITCH)} />
        <ToolBtn icon={<div className="w-3 h-3 rounded-full bg-green-500 shadow-[0_0_8px_#22c55e]" />} label="LED" onClick={() => onAddObject(ObjectType.LED)} />
      </div>

      {/* Properties Form */}
      <div className="flex-1 overflow-y-auto p-4 custom-scrollbar">
        {!selectedObject ? (
          <div className="flex flex-col items-center justify-center h-64 text-gray-600 opacity-50 space-y-3">
            <Box size={32} />
            <p className="text-[10px] font-black uppercase tracking-widest text-center">Select an object<br />to edit properties</p>
          </div>
        ) : (
          <div className="space-y-6">
            <div className="flex justify-between items-center">
              <h3 className="text-xs font-black text-blue-500 uppercase tracking-[2px]">Component Detail</h3>
              <button onClick={() => onDeleteObject(selectedObject.id)} className="p-1.5 text-red-500 hover:bg-red-500/10 rounded transition-colors">
                <Trash2 size={16} />
              </button>
            </div>

            <div className="bg-gray-950/50 p-4 rounded-xl border border-gray-800/50 space-y-4">
              {renderInput("Object Name", selectedObject.name, (val) => onUpdateObject(selectedObject.id, { name: val }))}

              {selectedObject.type === ObjectType.SWITCH && (
                <>
                  <div>
                    <label className="block text-[10px] text-gray-500 mb-1 font-bold uppercase tracking-wider">Assigned Input Port</label>
                    <select
                      className="w-full bg-gray-950 border border-gray-800 rounded px-2 py-1.5 text-sm text-white outline-none focus:border-blue-500"
                      value={(selectedObject as SwitchObject).inputPort}
                      onChange={(e) => onUpdateObject(selectedObject.id, { inputPort: parseInt(e.target.value) })}
                    >
                      {inputNames.map((name, i) => (
                        <option key={i} value={i}>X{i}: {name || '---'}</option>
                      ))}
                    </select>
                  </div>
                  <div className="flex items-center gap-2 pt-2">
                    <input type="checkbox" className="w-4 h-4 rounded bg-gray-900 border-gray-700" checked={(selectedObject as SwitchObject).isMomentary} onChange={(e) => onUpdateObject(selectedObject.id, { isMomentary: e.target.checked })} />
                    <span className="text-xs text-gray-300">Momentary Contact</span>
                  </div>
                </>
              )}

              {selectedObject.type === ObjectType.LED && (
                <>
                  <div>
                    <label className="block text-[10px] text-gray-500 mb-1 font-bold uppercase tracking-wider">Drive Output Port</label>
                    <select
                      className="w-full bg-gray-950 border border-gray-800 rounded px-2 py-1.5 text-sm text-white outline-none focus:border-blue-500"
                      value={(selectedObject as LedObject).outputPort}
                      onChange={(e) => onUpdateObject(selectedObject.id, { outputPort: parseInt(e.target.value) })}
                    >
                      {outputNames.map((name, i) => (
                        <option key={i} value={i}>Y{i}: {name || '---'}</option>
                      ))}
                    </select>
                  </div>
                  {renderInput("Light Color", (selectedObject as LedObject).color, (v) => onUpdateObject(selectedObject.id, { color: v }), "color")}
                </>
              )}

              {(selectedObject.type === ObjectType.AXIS_LINEAR || selectedObject.type === ObjectType.AXIS_ROTARY) && (
                <div>
                  <label className="block text-[10px] text-gray-500 mb-2 font-bold uppercase tracking-wider">Bind to Global Axis</label>
                  <select
                    className="w-full bg-gray-950 border border-gray-800 rounded px-2 py-1.5 text-sm text-white outline-none focus:border-blue-500"
                    value={(selectedObject as AxisObject).axisIndex}
                    onChange={(e) => onUpdateObject(selectedObject.id, { axisIndex: parseInt(e.target.value) })}
                  >
                    {axes.map((axis) => (
                      <option key={axis.id} value={axis.id}>
                        Channel {axis.id}: {axis.name} ({axis.type})
                      </option>
                    ))}
                  </select>

                  {/* Axis Control Slider in Sidebar */}
                  <div className="mt-4 p-3 bg-gray-900 rounded border border-gray-800">
                    <div className="flex justify-between items-end mb-2">
                      <span className="text-[10px] text-gray-500 font-bold uppercase tracking-wider">Manual Jog</span>
                      <span className="text-xs font-mono text-blue-400">
                        {axes[(selectedObject as AxisObject).axisIndex]?.value.toFixed(1) || '0.0'}
                      </span>
                    </div>
                    <input
                      type="range"
                      min={0}
                      max={axes[(selectedObject as AxisObject).axisIndex]?.type === 'rotary' ? 360 : 100}
                      step={0.1}
                      value={axes[(selectedObject as AxisObject).axisIndex]?.value || 0}
                      onChange={(e) => {
                        const val = parseFloat(e.target.value);
                        const idx = (selectedObject as AxisObject).axisIndex;
                        if (axes[idx]) {
                          onUpdateAxis(idx, { value: val, target: val });
                        }
                      }}
                      className="w-full h-2 bg-gray-800 rounded-lg appearance-none cursor-pointer accent-blue-500"
                    />
                  </div>
                </div>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

const ToolBtn: React.FC<{ icon: React.ReactNode, label: string, onClick: () => void }> = ({ icon, label, onClick }) => (
  <button
    onClick={onClick}
    className="flex flex-col items-center justify-center p-3 bg-gray-950 border border-gray-800 rounded-xl hover:bg-gray-800 hover:border-blue-500 hover:scale-[1.05] transition-all group"
  >
    <div className="mb-2 text-gray-400 group-hover:text-blue-400 transition-colors">{icon}</div>
    <span className="text-[9px] text-gray-500 font-black uppercase tracking-tight">{label}</span>
  </button>
);
