'use client'

import { useState } from 'react'
import { Component } from './types'
import { ComponentTypeIcon } from './ComponentTypeIcon'

export function ComponentTreeNode({
  component,
  depth,
  onEdit,
  onDelete,
  onAddChild,
  onMarkAbsent,
  onToggleCE,
}: {
  component: Component
  depth: number
  onEdit: (c: Component) => void
  onDelete: (id: string) => void
  onAddChild: (parentId: string) => void
  onMarkAbsent?: (id: string) => void
  onToggleCE?: (id: string, value: boolean) => void
}) {
  const ceMarked = !!component.ce_marked
  const safetyRelevant = !!(component.is_safety_relevant ?? component.safety_relevant)
  const [expanded, setExpanded] = useState(true)
  const hasChildren = component.children && component.children.length > 0

  return (
    <div>
      <div
        className="flex items-center gap-2 py-2 px-3 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 group transition-colors"
        style={{ paddingLeft: `${depth * 24 + 12}px` }}
      >
        <button
          onClick={() => setExpanded(!expanded)}
          className={`w-5 h-5 flex items-center justify-center text-gray-400 ${hasChildren ? 'visible' : 'invisible'}`}
        >
          <svg
            className={`w-4 h-4 transition-transform ${expanded ? 'rotate-90' : ''}`}
            fill="none" viewBox="0 0 24 24" stroke="currentColor"
          >
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
          </svg>
        </button>

        <ComponentTypeIcon type={component.type} />

        <div className="flex-1 min-w-0">
          <span className="text-sm font-medium text-gray-900 dark:text-white">{component.name}</span>
          {component.version && <span className="ml-2 text-xs text-gray-400">v{component.version}</span>}
          {component.safety_relevant && (
            <span className="ml-2 inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-red-100 text-red-700">
              Sicherheitsrelevant
            </span>
          )}
          {component.library_component_id && (
            <span className="ml-2 inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-purple-100 text-purple-700">
              Bibliothek
            </span>
          )}
          {ceMarked && (
            <span className="ml-2 inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-700"
              title="Zugekauft mit eigener CE / Konformitaetserklaerung — Nachweis via Hersteller-DoC">
              CE
            </span>
          )}
          {ceMarked && safetyRelevant && (
            <span className="ml-2 inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-amber-100 text-amber-800"
              title="Die CE der Box deckt die integrierte Sicherheitsfunktion NICHT — PL/SIL nach EN ISO 13849-1 / IEC 62061 muss validiert werden">
              ⚠ Sicherheitsfunktion validieren (PL/SIL)
            </span>
          )}
        </div>

        {component.description && (
          <span className="text-xs text-gray-400 truncate max-w-[200px] hidden lg:block">
            {component.description}
          </span>
        )}

        <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
          <button onClick={() => onAddChild(component.id)} title="Unterkomponente hinzufuegen"
            className="p-1 text-gray-400 hover:text-purple-600 hover:bg-purple-50 rounded transition-colors">
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
            </svg>
          </button>
          <button onClick={() => onEdit(component)} title="Bearbeiten"
            className="p-1 text-gray-400 hover:text-blue-600 hover:bg-blue-50 rounded transition-colors">
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
            </svg>
          </button>
          {onToggleCE && (
            <button onClick={() => onToggleCE(component.id, !ceMarked)}
              title={ceMarked ? 'CE-Markierung entfernen' : 'Als zugekaufte CE-Komponente markieren (Roboter/Aktor/SPS)'}
              className={`p-1 rounded transition-colors ${ceMarked ? 'text-blue-600 bg-blue-50' : 'text-gray-400 hover:text-blue-600 hover:bg-blue-50'}`}>
              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
            </button>
          )}
          {onMarkAbsent && (
            <button onClick={() => onMarkAbsent(component.id)} title="Als nicht vorhanden markieren"
              className="p-1 text-gray-400 hover:text-amber-600 hover:bg-amber-50 rounded transition-colors">
              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
              </svg>
            </button>
          )}
          <button onClick={() => onDelete(component.id)} title="Loeschen (in Geloescht verschieben)"
            className="p-1 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded transition-colors">
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
            </svg>
          </button>
        </div>
      </div>

      {expanded && hasChildren && (
        <div>
          {component.children.map((child) => (
            <ComponentTreeNode
              key={child.id}
              component={child}
              depth={depth + 1}
              onEdit={onEdit}
              onDelete={onDelete}
              onAddChild={onAddChild}
              onMarkAbsent={onMarkAbsent}
              onToggleCE={onToggleCE}
            />
          ))}
        </div>
      )}
    </div>
  )
}
