
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
} from '../types';

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

export const Sidebar: React.FC<SidebarProps> = ({
  objects,
  selectedId,
  isPlaying,
  inputNames,
  outputNames,
  onAddObject,
  onDeleteObject,
  onUpdateObject,
  onUpdatePortName,
  onExport,
  onImport
}) => {
  const [activeTab, setActiveTab] = useState<'properties' | 'system'>('properties');
  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">
      
      {/* Sub-navigation */}
      <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 className="flex bg-gray-800 p-1 rounded-lg">
          <button 
            onClick={() => setActiveTab('properties')}
            className={`px-3 py-1 rounded text-[10px] font-black uppercase ${activeTab === 'properties' ? 'bg-gray-600 text-white shadow' : 'text-gray-400 hover:text-gray-300'}`}
          >
            Props
          </button>
          <button 
            onClick={() => setActiveTab('system')}
            className={`px-3 py-1 rounded text-[10px] font-black uppercase ${activeTab === 'system' ? 'bg-gray-600 text-white shadow' : 'text-gray-400 hover:text-gray-300'}`}
          >
            System
          </button>
        </div>
      </div>

      {activeTab === 'properties' && (
        <>
          {/* 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">Manual Position ({(selectedObject as AxisObject).currentValue.toFixed(1)})</label>
                        <input type="range" min={(selectedObject as AxisObject).min} max={(selectedObject as AxisObject).max} value={(selectedObject as AxisObject).currentValue} step={0.1}
                          onChange={(e) => onUpdateObject(selectedObject.id, { currentValue: parseFloat(e.target.value), targetValue: parseFloat(e.target.value) })} 
                          className="w-full h-1.5 bg-gray-800 rounded-lg appearance-none cursor-pointer accent-blue-500" />
                    </div>
                  )}
                </div>
              </div>
            )}
          </div>
        </>
      )}

      {activeTab === 'system' && (
        <div className="flex-1 overflow-y-auto p-4 custom-scrollbar flex flex-col gap-6">
          <div className="grid grid-cols-2 gap-2">
             <button onClick={onExport} className="bg-blue-600 hover:bg-blue-500 py-2.5 rounded-lg text-xs font-bold flex items-center justify-center gap-2 transition-all shadow-lg shadow-blue-900/20">
               <Download size={14}/> EXPORT
             </button>
             <label className="bg-purple-600 hover:bg-purple-500 py-2.5 rounded-lg text-xs font-bold flex items-center justify-center gap-2 cursor-pointer transition-all shadow-lg shadow-purple-900/20">
               <Upload size={14}/> IMPORT
               <input type="file" className="hidden" accept=".json" onChange={onImport} />
             </label>
          </div>

          <div className="space-y-4">
            <h3 className="text-[10px] font-black text-gray-500 uppercase tracking-widest border-b border-gray-800 pb-2">Hardware Mapping</h3>
            
            <div className="space-y-6">
              <div>
                <h4 className="text-[10px] font-bold text-green-500 mb-3 uppercase flex items-center gap-2">
                  <div className="w-1.5 h-1.5 rounded-full bg-green-500"/> Inputs (X0 - X15)
                </h4>
                <div className="grid gap-1">
                  {inputNames.map((name, i) => (
                    <div key={i} className="flex items-center gap-2 group">
                      <span className="w-6 text-[9px] text-gray-600 font-mono">X{i.toString().padStart(2, '0')}</span>
                      <input 
                        className="flex-1 bg-gray-950 border border-gray-800 rounded px-2 py-1 text-[11px] focus:border-green-500 outline-none transition-colors"
                        placeholder="Tag name..."
                        value={name}
                        onChange={(e) => onUpdatePortName('input', i, e.target.value)}
                      />
                    </div>
                  ))}
                </div>
              </div>

              <div>
                <h4 className="text-[10px] font-bold text-red-500 mb-3 uppercase flex items-center gap-2">
                   <div className="w-1.5 h-1.5 rounded-full bg-red-500"/> Outputs (Y0 - Y15)
                </h4>
                <div className="grid gap-1">
                  {outputNames.map((name, i) => (
                    <div key={i} className="flex items-center gap-2 group">
                      <span className="w-6 text-[9px] text-gray-600 font-mono">Y{i.toString().padStart(2, '0')}</span>
                      <input 
                        className="flex-1 bg-gray-950 border border-gray-800 rounded px-2 py-1 text-[11px] focus:border-red-500 outline-none transition-colors"
                        placeholder="Tag name..."
                        value={name}
                        onChange={(e) => onUpdatePortName('output', i, e.target.value)}
                      />
                    </div>
                  ))}
                </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>
);
