import { useState } from 'react';
import { Eye, EyeOff, Trash2, Plus, ChevronRight, ChevronDown } from 'lucide-react';
import { useMeshStore } from '../stores/meshStore';

interface LayerPanelProps {
  onAddFile: () => void;
}

export function LayerPanel({ onAddFile }: LayerPanelProps) {
  const { state, dispatch } = useMeshStore();
  const [expandedId, setExpandedId] = useState<string | null>(null);

  return (
    <div
      data-testid="layer-panel"
      style={{
        height: '100%', display: 'flex', flexDirection: 'column',
        background: '#ffffff', color: '#222', fontSize: 12, fontFamily: 'system-ui, sans-serif',
      }}
    >
      <div style={{
        padding: '6px 10px', fontWeight: 'bold', borderBottom: '1px solid #c0c0c0',
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        background: '#e8e8e8',
      }}>
        Layers
        <button data-testid="add-layer" onClick={onAddFile}
          style={{ background: 'none', border: 'none', color: '#555', cursor: 'pointer', padding: 2 }} title="Add layer">
          <Plus size={14} />
        </button>
      </div>

      <div style={{ flex: 1, overflowY: 'auto' }}>
        {state.layers.map((layer, idx) => {
          const isActive = layer.id === state.activeLayerId;
          const isExpanded = expandedId === layer.id;

          return (
            <div key={layer.id}>
              <div
                data-testid="layer-item"
                data-testid2={`layer-row`}
                onClick={() => {
                  dispatch({ type: 'SET_ACTIVE_LAYER', id: layer.id });
                  setExpandedId(isExpanded ? null : layer.id);
                }}
                style={{
                  display: 'flex', alignItems: 'center', gap: 4, padding: '4px 6px',
                  cursor: 'pointer', background: isActive ? '#c0d8f0' : 'transparent',
                  borderBottom: '1px solid #ddd',
                }}
              >
                {isExpanded ? <ChevronDown size={12} /> : <ChevronRight size={12} />}
                <span style={{ color: '#999', fontSize: 10, width: 14, textAlign: 'right' }}>{idx}</span>
                <button
                  data-testid={`layer-visibility-${idx}`}
                  onClick={(e) => { e.stopPropagation(); dispatch({ type: 'TOGGLE_VISIBILITY', id: layer.id }); }}
                  style={{ background: 'none', border: 'none', color: '#555', cursor: 'pointer', padding: 0 }}
                  title={layer.visible ? 'Hide' : 'Show'}
                >
                  {layer.visible ? <Eye size={13} /> : <EyeOff size={13} />}
                </button>
                <div style={{ flex: 1, overflow: 'hidden' }}>
                  <div style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                    {layer.name}
                  </div>
                </div>
                <button
                  data-testid={`layer-delete-${idx}`}
                  onClick={(e) => { e.stopPropagation(); dispatch({ type: 'REMOVE_LAYER', id: layer.id }); }}
                  style={{ background: 'none', border: 'none', color: '#999', cursor: 'pointer', padding: 0 }}
                  title="Delete"
                >
                  <Trash2 size={12} />
                </button>
              </div>

              {/* Expanded details */}
              {isExpanded && (
                <div data-testid="layer-details" style={{
                  padding: '4px 10px 8px 28px', borderBottom: '1px solid #ddd',
                  background: '#f8f8f8', fontSize: 11, lineHeight: 1.6, color: '#333',
                }}>
                  <div>File: <span style={{ color: '#555' }}>{layer.name}</span></div>
                  <div>Vertices: <span style={{ color: '#555' }}>{layer.vertexCount.toLocaleString()}</span></div>
                  <div>Faces: <span style={{ color: '#555' }}>{layer.faceCount.toLocaleString()}</span></div>
                  <div>Handle: <span style={{ color: '#555' }}>{layer.wasmHandle >= 0 ? `wasm:${layer.wasmHandle}` : 'js'}</span></div>
                  {layer.fileSize > 0 && (
                    <div>Size: <span style={{ color: '#aaa' }}>{(layer.fileSize / 1024).toFixed(1)} KB</span></div>
                  )}
                </div>
              )}
            </div>
          );
        })}
        {state.layers.length === 0 && (
          <div style={{ padding: 12, color: '#999', textAlign: 'center' }}>
            No layers. Drop a file or click +
          </div>
        )}
      </div>
    </div>
  );
}
