'use client'

import React from 'react'
import { ARCH_SERVICES, LAYERS, type ArchService } from '../architecture-data'
import { type LayerFilter } from '../_layout'

export default function ServiceTable({
  layerFilter,
  expandedServices,
  onToggleExpanded,
  onMarkInGraph,
}: {
  layerFilter: LayerFilter
  expandedServices: Set<string>
  onToggleExpanded: (id: string) => void
  onMarkInGraph: (service: ArchService) => void
}) {
  const filtered = ARCH_SERVICES.filter(
    s => layerFilter === 'alle' || s.layer === layerFilter
  )

  return (
    <div className="bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden">
      <div className="px-4 py-3 bg-slate-50 border-b">
        <h3 className="font-medium text-slate-700">
          Alle Services ({
            layerFilter === 'alle'
              ? ARCH_SERVICES.length
              : `${ARCH_SERVICES.filter(s => s.layer === layerFilter).length} / ${ARCH_SERVICES.length}`
          })
        </h3>
      </div>
      <div className="divide-y max-h-[600px] overflow-y-auto">
        {filtered.map(service => {
          const layer = LAYERS[service.layer]
          const isExpanded = expandedServices.has(service.id)

          return (
            <div key={service.id}>
              {/* Row Header */}
              <button
                onClick={() => onToggleExpanded(service.id)}
                className={`w-full flex items-center gap-3 p-3 text-left transition-colors ${
                  isExpanded
                    ? 'bg-purple-50'
                    : 'hover:bg-slate-50'
                }`}
              >
                {/* Chevron */}
                <svg
                  className={`w-4 h-4 text-slate-400 shrink-0 transition-transform duration-200 ${
                    isExpanded ? 'rotate-90' : ''
                  }`}
                  fill="none" stroke="currentColor" viewBox="0 0 24 24"
                >
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                </svg>
                <span
                  className="w-8 h-8 rounded-lg flex items-center justify-center text-[10px] font-bold shrink-0"
                  style={{ background: layer.colorBg, color: layer.colorText }}
                >
                  {service.port ? `:${service.port}` : '--'}
                </span>
                <div className="flex-1 min-w-0">
                  <div className="font-medium text-slate-800 text-sm">
                    {service.name}
                  </div>
                  <div className="text-xs text-slate-500 flex items-center gap-2 mt-0.5">
                    <span className="text-slate-400">{service.tech}</span>
                    {service.dbTables.length > 0 && (
                      <span className="text-slate-400">
                        DB: {service.dbTables.length}
                      </span>
                    )}
                    {service.ragCollections.length > 0 && (
                      <span className="text-green-600">
                        RAG: {service.ragCollections.length}
                      </span>
                    )}
                    {service.apiEndpoints.length > 0 && (
                      <span className="text-violet-600">
                        API: {service.apiEndpoints.length}
                      </span>
                    )}
                  </div>
                </div>
                <code className="text-[10px] text-slate-400 shrink-0 hidden sm:block">
                  {service.container}
                </code>
                <span
                  className="px-2 py-0.5 rounded text-[10px] font-medium shrink-0"
                  style={{ background: layer.colorBg, color: layer.colorText }}
                >
                  {layer.name}
                </span>
              </button>

              {/* Expanded Detail */}
              {isExpanded && <ExpandedRow service={service} onMarkInGraph={onMarkInGraph} />}
            </div>
          )
        })}
      </div>
    </div>
  )
}

function ExpandedRow({
  service,
  onMarkInGraph,
}: {
  service: ArchService
  onMarkInGraph: (service: ArchService) => void
}) {
  return (
    <div className="px-4 pb-4 pt-1 bg-slate-50/50 border-t border-slate-100">
      {/* Beschreibung */}
      <p className="text-sm text-slate-700 leading-relaxed">
        {service.description}
      </p>
      <p className="text-xs text-slate-500 leading-relaxed mt-1 mb-3">
        {service.descriptionLong}
      </p>

      {/* Info Grid */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 mb-3">
        <div className="bg-white rounded-lg border border-slate-200 p-2.5">
          <div className="text-[10px] font-semibold text-slate-400 uppercase">Tech</div>
          <div className="text-sm font-medium text-slate-800 mt-0.5">{service.tech}</div>
        </div>
        <div className="bg-white rounded-lg border border-slate-200 p-2.5">
          <div className="text-[10px] font-semibold text-slate-400 uppercase">Port</div>
          <div className="text-sm font-medium text-slate-800 mt-0.5">
            {service.port ? `:${service.port}` : 'Intern'}
          </div>
        </div>
        <div className="bg-white rounded-lg border border-slate-200 p-2.5">
          <div className="text-[10px] font-semibold text-slate-400 uppercase">Container</div>
          <div className="text-xs font-mono text-slate-700 mt-0.5 truncate">{service.container}</div>
        </div>
        {service.url && (
          <div className="bg-white rounded-lg border border-slate-200 p-2.5">
            <div className="text-[10px] font-semibold text-slate-400 uppercase">URL</div>
            <a
              href={service.url}
              target="_blank"
              rel="noopener noreferrer"
              className="text-xs text-blue-600 hover:underline mt-0.5 block truncate"
            >
              {service.url}
            </a>
          </div>
        )}
      </div>

      {/* Sections */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
        {service.dbTables.length > 0 && (
          <div className="bg-white rounded-lg border border-slate-200 p-3">
            <h4 className="text-[10px] font-semibold text-slate-500 uppercase mb-2">
              DB-Tabellen ({service.dbTables.length})
            </h4>
            <div className="space-y-1 max-h-40 overflow-y-auto">
              {service.dbTables.map(table => (
                <div key={table} className="bg-slate-50 rounded px-2 py-1">
                  <code className="text-xs text-slate-700">{table}</code>
                </div>
              ))}
            </div>
          </div>
        )}

        {service.ragCollections.length > 0 && (
          <div className="bg-white rounded-lg border border-slate-200 p-3">
            <h4 className="text-[10px] font-semibold text-slate-500 uppercase mb-2">
              RAG-Collections ({service.ragCollections.length})
            </h4>
            <div className="space-y-1">
              {service.ragCollections.map(rag => (
                <div key={rag} className="bg-green-50 rounded px-2 py-1">
                  <code className="text-xs text-green-700">{rag}</code>
                </div>
              ))}
            </div>
          </div>
        )}

        {service.apiEndpoints.length > 0 && (
          <div className="bg-white rounded-lg border border-slate-200 p-3">
            <h4 className="text-[10px] font-semibold text-slate-500 uppercase mb-2">
              API-Endpunkte ({service.apiEndpoints.length})
            </h4>
            <div className="space-y-1 max-h-40 overflow-y-auto">
              {service.apiEndpoints.map(ep => (
                <div key={ep} className="bg-violet-50 rounded px-2 py-1">
                  <code className="text-xs text-violet-700">{ep}</code>
                </div>
              ))}
            </div>
          </div>
        )}

        {service.dependsOn.length > 0 && (
          <div className="bg-white rounded-lg border border-slate-200 p-3">
            <h4 className="text-[10px] font-semibold text-slate-500 uppercase mb-2">
              Abhaengigkeiten ({service.dependsOn.length})
            </h4>
            <div className="space-y-1">
              {service.dependsOn.map(depId => {
                const dep = ARCH_SERVICES.find(s => s.id === depId)
                const depLayer = dep ? LAYERS[dep.layer] : null
                return (
                  <div key={depId} className="flex items-center gap-2 bg-slate-50 rounded px-2 py-1">
                    {depLayer && (
                      <span
                        className="w-2 h-2 rounded-full shrink-0"
                        style={{ background: depLayer.colorBorder }}
                      />
                    )}
                    <span className="text-xs text-slate-700">{dep?.name || depId}</span>
                  </div>
                )
              })}
            </div>
          </div>
        )}
      </div>

      {/* Open in Graph + URL */}
      <div className="flex items-center gap-2 mt-3">
        <button
          onClick={() => {
            onMarkInGraph(service)
            window.scrollTo({ top: 0, behavior: 'smooth' })
          }}
          className="px-3 py-1.5 bg-slate-100 text-slate-700 rounded-lg text-xs font-medium hover:bg-slate-200 transition-colors"
        >
          Im Graph markieren
        </button>
        {service.url && (
          <a
            href={service.url}
            target="_blank"
            rel="noopener noreferrer"
            className="px-3 py-1.5 bg-purple-600 text-white rounded-lg text-xs font-medium hover:bg-purple-700 transition-colors"
          >
            Service oeffnen
          </a>
        )}
      </div>
    </div>
  )
}
