'use client'

import React, { useState, useEffect } from 'react'
import { useParams } from 'next/navigation'

interface Component {
  id: string
  name: string
  type: string
  version: string
  description: string
  safety_relevant: boolean
  parent_id: string | null
  children: Component[]
}

const COMPONENT_TYPES = [
  { value: 'SW', label: 'Software (SW)' },
  { value: 'FW', label: 'Firmware (FW)' },
  { value: 'AI', label: 'KI-Modul (AI)' },
  { value: 'HMI', label: 'Mensch-Maschine-Schnittstelle (HMI)' },
  { value: 'SENSOR', label: 'Sensor' },
  { value: 'ACTUATOR', label: 'Aktor' },
  { value: 'CONTROLLER', label: 'Steuerung' },
  { value: 'NETWORK', label: 'Netzwerk' },
  { value: 'MECHANICAL', label: 'Mechanik' },
  { value: 'ELECTRICAL', label: 'Elektrik' },
  { value: 'OTHER', label: 'Sonstiges' },
]

function ComponentTypeIcon({ type }: { type: string }) {
  const colors: Record<string, string> = {
    SW: 'bg-blue-100 text-blue-700',
    FW: 'bg-indigo-100 text-indigo-700',
    AI: 'bg-purple-100 text-purple-700',
    HMI: 'bg-pink-100 text-pink-700',
    SENSOR: 'bg-cyan-100 text-cyan-700',
    ACTUATOR: 'bg-orange-100 text-orange-700',
    CONTROLLER: 'bg-green-100 text-green-700',
    NETWORK: 'bg-yellow-100 text-yellow-700',
    MECHANICAL: 'bg-gray-100 text-gray-700',
    ELECTRICAL: 'bg-red-100 text-red-700',
    OTHER: 'bg-gray-100 text-gray-500',
  }
  return (
    <span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${colors[type] || colors.OTHER}`}>
      {type}
    </span>
  )
}

function ComponentTreeNode({
  component,
  depth,
  onEdit,
  onDelete,
  onAddChild,
}: {
  component: Component
  depth: number
  onEdit: (c: Component) => void
  onDelete: (id: string) => void
  onAddChild: (parentId: string) => void
}) {
  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` }}
      >
        {/* Expand/collapse */}
        <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>
          )}
        </div>

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

        {/* Actions */}
        <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>
          <button
            onClick={() => onDelete(component.id)}
            title="Loeschen"
            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}
            />
          ))}
        </div>
      )}
    </div>
  )
}

interface ComponentFormData {
  name: string
  type: string
  version: string
  description: string
  safety_relevant: boolean
  parent_id: string | null
}

function ComponentForm({
  onSubmit,
  onCancel,
  initialData,
  parentId,
}: {
  onSubmit: (data: ComponentFormData) => void
  onCancel: () => void
  initialData?: Component | null
  parentId?: string | null
}) {
  const [formData, setFormData] = useState<ComponentFormData>({
    name: initialData?.name || '',
    type: initialData?.type || 'SW',
    version: initialData?.version || '',
    description: initialData?.description || '',
    safety_relevant: initialData?.safety_relevant || false,
    parent_id: parentId || initialData?.parent_id || null,
  })

  return (
    <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6">
      <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
        {initialData ? 'Komponente bearbeiten' : parentId ? 'Unterkomponente hinzufuegen' : 'Neue Komponente'}
      </h3>
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Name *</label>
          <input
            type="text"
            value={formData.name}
            onChange={(e) => setFormData({ ...formData, name: e.target.value })}
            placeholder="z.B. Bildverarbeitungsmodul"
            className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent dark:bg-gray-700 dark:border-gray-600 dark:text-white"
          />
        </div>
        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Typ</label>
          <select
            value={formData.type}
            onChange={(e) => setFormData({ ...formData, type: e.target.value })}
            className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent dark:bg-gray-700 dark:border-gray-600 dark:text-white"
          >
            {COMPONENT_TYPES.map((t) => (
              <option key={t.value} value={t.value}>{t.label}</option>
            ))}
          </select>
        </div>
        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Version</label>
          <input
            type="text"
            value={formData.version}
            onChange={(e) => setFormData({ ...formData, version: e.target.value })}
            placeholder="z.B. 1.2.0"
            className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent dark:bg-gray-700 dark:border-gray-600 dark:text-white"
          />
        </div>
        <div className="flex items-center gap-3 pt-6">
          <label className="relative inline-flex items-center cursor-pointer">
            <input
              type="checkbox"
              checked={formData.safety_relevant}
              onChange={(e) => setFormData({ ...formData, safety_relevant: e.target.checked })}
              className="sr-only peer"
            />
            <div className="w-9 h-5 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-purple-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-red-500" />
          </label>
          <span className="text-sm text-gray-700 dark:text-gray-300">Sicherheitsrelevant</span>
        </div>
        <div className="md:col-span-2">
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Beschreibung</label>
          <textarea
            value={formData.description}
            onChange={(e) => setFormData({ ...formData, description: e.target.value })}
            placeholder="Kurze Beschreibung der Komponente..."
            rows={2}
            className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent dark:bg-gray-700 dark:border-gray-600 dark:text-white"
          />
        </div>
      </div>
      <div className="mt-4 flex items-center gap-3">
        <button
          onClick={() => onSubmit(formData)}
          disabled={!formData.name}
          className={`px-6 py-2 rounded-lg font-medium transition-colors ${
            formData.name
              ? 'bg-purple-600 text-white hover:bg-purple-700'
              : 'bg-gray-200 text-gray-400 cursor-not-allowed'
          }`}
        >
          {initialData ? 'Aktualisieren' : 'Hinzufuegen'}
        </button>
        <button
          onClick={onCancel}
          className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors"
        >
          Abbrechen
        </button>
      </div>
    </div>
  )
}

function buildTree(components: Component[]): Component[] {
  const map = new Map<string, Component>()
  const roots: Component[] = []

  components.forEach((c) => {
    map.set(c.id, { ...c, children: [] })
  })

  components.forEach((c) => {
    const node = map.get(c.id)!
    if (c.parent_id && map.has(c.parent_id)) {
      map.get(c.parent_id)!.children.push(node)
    } else {
      roots.push(node)
    }
  })

  return roots
}

export default function ComponentsPage() {
  const params = useParams()
  const projectId = params.projectId as string
  const [components, setComponents] = useState<Component[]>([])
  const [loading, setLoading] = useState(true)
  const [showForm, setShowForm] = useState(false)
  const [editingComponent, setEditingComponent] = useState<Component | null>(null)
  const [addingParentId, setAddingParentId] = useState<string | null>(null)

  useEffect(() => {
    fetchComponents()
  }, [projectId])

  async function fetchComponents() {
    try {
      const res = await fetch(`/api/sdk/v1/iace/projects/${projectId}/components`)
      if (res.ok) {
        const json = await res.json()
        setComponents(json.components || json || [])
      }
    } catch (err) {
      console.error('Failed to fetch components:', err)
    } finally {
      setLoading(false)
    }
  }

  async function handleSubmit(data: ComponentFormData) {
    try {
      const url = editingComponent
        ? `/api/sdk/v1/iace/projects/${projectId}/components/${editingComponent.id}`
        : `/api/sdk/v1/iace/projects/${projectId}/components`
      const method = editingComponent ? 'PUT' : 'POST'

      const res = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data),
      })
      if (res.ok) {
        setShowForm(false)
        setEditingComponent(null)
        setAddingParentId(null)
        await fetchComponents()
      }
    } catch (err) {
      console.error('Failed to save component:', err)
    }
  }

  async function handleDelete(id: string) {
    if (!confirm('Komponente wirklich loeschen? Unterkomponenten werden ebenfalls entfernt.')) return
    try {
      const res = await fetch(`/api/sdk/v1/iace/projects/${projectId}/components/${id}`, {
        method: 'DELETE',
      })
      if (res.ok) {
        await fetchComponents()
      }
    } catch (err) {
      console.error('Failed to delete component:', err)
    }
  }

  function handleEdit(component: Component) {
    setEditingComponent(component)
    setAddingParentId(null)
    setShowForm(true)
  }

  function handleAddChild(parentId: string) {
    setAddingParentId(parentId)
    setEditingComponent(null)
    setShowForm(true)
  }

  const tree = buildTree(components)

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600" />
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Komponenten</h1>
          <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
            Erfassen Sie alle Software-, Firmware-, KI- und Hardware-Komponenten der Maschine.
          </p>
        </div>
        {!showForm && (
          <button
            onClick={() => {
              setShowForm(true)
              setEditingComponent(null)
              setAddingParentId(null)
            }}
            className="flex items-center gap-2 px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors"
          >
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
            </svg>
            Komponente hinzufuegen
          </button>
        )}
      </div>

      {/* Form */}
      {showForm && (
        <ComponentForm
          onSubmit={handleSubmit}
          onCancel={() => {
            setShowForm(false)
            setEditingComponent(null)
            setAddingParentId(null)
          }}
          initialData={editingComponent}
          parentId={addingParentId}
        />
      )}

      {/* Component Tree */}
      {tree.length > 0 ? (
        <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 divide-y divide-gray-100 dark:divide-gray-700">
          <div className="px-4 py-3 bg-gray-50 dark:bg-gray-750 rounded-t-xl">
            <div className="flex items-center gap-2 text-xs font-medium text-gray-500 uppercase tracking-wider">
              <span className="w-5" />
              <span>Typ</span>
              <span className="flex-1">Name</span>
              <span className="hidden lg:block w-[200px]">Beschreibung</span>
              <span className="w-24">Aktionen</span>
            </div>
          </div>
          <div className="py-1">
            {tree.map((component) => (
              <ComponentTreeNode
                key={component.id}
                component={component}
                depth={0}
                onEdit={handleEdit}
                onDelete={handleDelete}
                onAddChild={handleAddChild}
              />
            ))}
          </div>
        </div>
      ) : (
        !showForm && (
          <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-12 text-center">
            <div className="w-16 h-16 mx-auto bg-purple-100 dark:bg-purple-900/30 rounded-full flex items-center justify-center mb-4">
              <svg className="w-8 h-8 text-purple-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
              </svg>
            </div>
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white">Keine Komponenten erfasst</h3>
            <p className="mt-2 text-gray-500 max-w-md mx-auto">
              Beginnen Sie mit der Erfassung aller relevanten Komponenten Ihrer Maschine.
              Erstellen Sie eine hierarchische Struktur aus Software, Firmware, KI-Modulen und Hardware.
            </p>
            <button
              onClick={() => setShowForm(true)}
              className="mt-6 px-6 py-3 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors"
            >
              Erste Komponente hinzufuegen
            </button>
          </div>
        )
      )}
    </div>
  )
}
