'use client'

import { useState, useMemo, useRef } from 'react'
import { apiModules } from '@/lib/sdk/api-docs/endpoints'
import type { HttpMethod, BackendService, ApiExposure } from '@/lib/sdk/api-docs/types'

const METHOD_COLORS: Record<HttpMethod, string> = {
  GET: 'bg-green-100 text-green-800',
  POST: 'bg-blue-100 text-blue-800',
  PUT: 'bg-yellow-100 text-yellow-800',
  DELETE: 'bg-red-100 text-red-800',
  PATCH: 'bg-purple-100 text-purple-800',
}

const EXPOSURE_CONFIG: Record<ApiExposure, { label: string; color: string; description: string }> = {
  public: { label: 'Oeffentlich', color: 'bg-green-100 text-green-800 border-green-200', description: 'Internet-exponiert' },
  partner: { label: 'Integration', color: 'bg-blue-100 text-blue-800 border-blue-200', description: 'API-Key/OAuth' },
  internal: { label: 'Intern', color: 'bg-gray-100 text-gray-700 border-gray-200', description: 'Nur Admin' },
  admin: { label: 'Wartung', color: 'bg-orange-100 text-orange-800 border-orange-200', description: 'Nur Setup' },
}

type ServiceFilter = 'all' | BackendService
type ExposureFilter = 'all' | ApiExposure

function ExposureBadge({ exposure }: { exposure: ApiExposure }) {
  const config = EXPOSURE_CONFIG[exposure]
  return (
    <span className={`inline-block text-[10px] font-medium px-1.5 py-0.5 rounded border ${config.color}`}>
      {config.label}
    </span>
  )
}

export default function ApiDocsPage() {
  const [search, setSearch] = useState('')
  const [serviceFilter, setServiceFilter] = useState<ServiceFilter>('all')
  const [methodFilter, setMethodFilter] = useState<HttpMethod | 'all'>('all')
  const [exposureFilter, setExposureFilter] = useState<ExposureFilter>('all')
  const [expandedModules, setExpandedModules] = useState<Set<string>>(new Set())
  const moduleRefs = useRef<Record<string, HTMLDivElement | null>>({})

  const filteredModules = useMemo(() => {
    const q = search.toLowerCase()
    return apiModules
      .filter((m) => serviceFilter === 'all' || m.service === serviceFilter)
      .filter((m) => {
        if (exposureFilter === 'all') return true
        if (m.exposure === exposureFilter) return true
        return m.endpoints.some((e) => (e.exposure || m.exposure) === exposureFilter)
      })
      .map((m) => {
        const eps = m.endpoints.filter((e) => {
          if (methodFilter !== 'all' && e.method !== methodFilter) return false
          if (exposureFilter !== 'all' && (e.exposure || m.exposure) !== exposureFilter) return false
          if (!q) return true
          return (
            e.path.toLowerCase().includes(q) ||
            e.description.toLowerCase().includes(q) ||
            m.name.toLowerCase().includes(q) ||
            m.id.toLowerCase().includes(q)
          )
        })
        return { ...m, endpoints: eps }
      })
      .filter((m) => m.endpoints.length > 0)
  }, [search, serviceFilter, methodFilter, exposureFilter])

  const stats = useMemo(() => {
    const total = apiModules.reduce((s, m) => s + m.endpoints.length, 0)
    const python = apiModules.filter((m) => m.service === 'python').reduce((s, m) => s + m.endpoints.length, 0)
    const go = apiModules.filter((m) => m.service === 'go').reduce((s, m) => s + m.endpoints.length, 0)

    const exposureCounts = { public: 0, partner: 0, internal: 0, admin: 0 }
    apiModules.forEach((m) => {
      m.endpoints.forEach((e) => {
        const exp = e.exposure || m.exposure
        exposureCounts[exp]++
      })
    })

    return { total, python, go, modules: apiModules.length, exposure: exposureCounts }
  }, [])

  const filteredTotal = filteredModules.reduce((s, m) => s + m.endpoints.length, 0)

  const toggleModule = (id: string) => {
    setExpandedModules((prev) => {
      const next = new Set(prev)
      if (next.has(id)) next.delete(id)
      else next.add(id)
      return next
    })
  }

  const expandAll = () => setExpandedModules(new Set(filteredModules.map((m) => m.id)))
  const collapseAll = () => setExpandedModules(new Set())

  const scrollToModule = (id: string) => {
    setExpandedModules((prev) => new Set([...prev, id]))
    setTimeout(() => {
      moduleRefs.current[id]?.scrollIntoView({ behavior: 'smooth', block: 'start' })
    }, 100)
  }

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <div className="bg-white border-b border-gray-200 sticky top-0 z-20">
        <div className="max-w-7xl mx-auto px-4 py-4">
          <div className="flex items-center justify-between mb-3">
            <div>
              <h1 className="text-xl font-bold text-gray-900">API-Referenz</h1>
              <p className="text-sm text-gray-500 mt-0.5">
                {stats.total} Endpoints in {stats.modules} Modulen
              </p>
            </div>
            <div className="flex gap-2">
              <button
                onClick={expandAll}
                className="px-3 py-1.5 text-xs font-medium text-gray-600 bg-gray-100 rounded-lg hover:bg-gray-200 transition-colors"
              >
                Alle aufklappen
              </button>
              <button
                onClick={collapseAll}
                className="px-3 py-1.5 text-xs font-medium text-gray-600 bg-gray-100 rounded-lg hover:bg-gray-200 transition-colors"
              >
                Alle zuklappen
              </button>
            </div>
          </div>

          {/* Exposure Stats */}
          <div className="flex flex-wrap gap-2 mb-3 text-xs">
            <span className="text-gray-500">Exposure:</span>
            <span className="px-2 py-0.5 rounded bg-green-50 text-green-700 font-medium">
              {stats.exposure.public} oeffentlich
            </span>
            <span className="px-2 py-0.5 rounded bg-blue-50 text-blue-700 font-medium">
              {stats.exposure.partner} Integration
            </span>
            <span className="px-2 py-0.5 rounded bg-gray-100 text-gray-600 font-medium">
              {stats.exposure.internal} intern
            </span>
            <span className="px-2 py-0.5 rounded bg-orange-50 text-orange-700 font-medium">
              {stats.exposure.admin} Wartung
            </span>
            <span className="text-gray-400 ml-1">
              ({Math.round((stats.exposure.public + stats.exposure.partner) / stats.total * 100)}% exponiert)
            </span>
          </div>

          {/* Search + Filters */}
          <div className="flex flex-wrap gap-3 items-center">
            <div className="relative flex-1 min-w-[240px]">
              <svg
                className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
              </svg>
              <input
                type="text"
                placeholder="Endpoint, Beschreibung oder Modul suchen..."
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                className="w-full pl-9 pr-4 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              />
              {search && (
                <button
                  onClick={() => setSearch('')}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
                >
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                  </svg>
                </button>
              )}
            </div>

            {/* Service Filter */}
            <div className="flex rounded-lg border border-gray-300 overflow-hidden">
              {([['all', 'Alle'], ['python', 'Python/FastAPI'], ['go', 'Go/Gin']] as const).map(([val, label]) => (
                <button
                  key={val}
                  onClick={() => setServiceFilter(val)}
                  className={`px-3 py-2 text-xs font-medium transition-colors ${
                    serviceFilter === val
                      ? 'bg-gray-900 text-white'
                      : 'bg-white text-gray-600 hover:bg-gray-50'
                  }`}
                >
                  {label}
                </button>
              ))}
            </div>

            {/* Exposure Filter */}
            <div className="flex rounded-lg border border-gray-300 overflow-hidden">
              {([
                ['all', 'Alle'],
                ['public', 'Oeffentlich'],
                ['partner', 'Integration'],
                ['internal', 'Intern'],
                ['admin', 'Wartung'],
              ] as const).map(([val, label]) => (
                <button
                  key={val}
                  onClick={() => setExposureFilter(val)}
                  className={`px-3 py-2 text-xs font-medium transition-colors ${
                    exposureFilter === val
                      ? 'bg-gray-900 text-white'
                      : 'bg-white text-gray-600 hover:bg-gray-50'
                  }`}
                >
                  {label}
                </button>
              ))}
            </div>

            {/* Method Filter */}
            <div className="flex gap-1.5">
              {(['all', 'GET', 'POST', 'PUT', 'DELETE', 'PATCH'] as const).map((m) => (
                <button
                  key={m}
                  onClick={() => setMethodFilter(m)}
                  className={`px-2.5 py-1.5 text-xs font-mono font-bold rounded-md transition-colors ${
                    methodFilter === m
                      ? m === 'all'
                        ? 'bg-gray-900 text-white'
                        : METHOD_COLORS[m] + ' ring-2 ring-offset-1 ring-gray-400'
                      : 'bg-gray-100 text-gray-500 hover:bg-gray-200'
                  }`}
                >
                  {m === 'all' ? 'ALLE' : m}
                </button>
              ))}
            </div>
          </div>
        </div>
      </div>

      <div className="max-w-7xl mx-auto px-4 py-6">
        {/* Stats Cards */}
        <div className="grid grid-cols-4 gap-4 mb-6">
          {[
            { label: 'Endpoints gesamt', value: stats.total, color: 'text-gray-900' },
            { label: 'Python / FastAPI', value: stats.python, color: 'text-blue-700' },
            { label: 'Go / Gin', value: stats.go, color: 'text-emerald-700' },
            { label: 'Module', value: stats.modules, color: 'text-purple-700' },
          ].map((s) => (
            <div key={s.label} className="bg-white rounded-lg border border-gray-200 p-4">
              <p className="text-xs text-gray-500 mb-1">{s.label}</p>
              <p className={`text-2xl font-bold ${s.color}`}>{s.value}</p>
            </div>
          ))}
        </div>

        <div className="flex gap-6">
          {/* Module Index (Sidebar) */}
          <div className="hidden lg:block w-64 flex-shrink-0">
            <div className="bg-white rounded-lg border border-gray-200 p-4 sticky top-[170px] max-h-[calc(100vh-210px)] overflow-y-auto">
              <h3 className="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-3">
                Modul-Index ({filteredModules.length})
              </h3>
              <div className="space-y-0.5">
                {filteredModules.map((m) => (
                  <button
                    key={m.id}
                    onClick={() => scrollToModule(m.id)}
                    className="w-full text-left px-2 py-1.5 text-xs rounded hover:bg-gray-100 transition-colors group flex items-center justify-between gap-1"
                  >
                    <span className="truncate text-gray-700 group-hover:text-gray-900">
                      {m.id}
                    </span>
                    <span className="flex items-center gap-1 flex-shrink-0">
                      <ExposureBadge exposure={m.exposure} />
                      <span className={`text-[10px] px-1.5 py-0.5 rounded-full ${
                        m.service === 'python' ? 'bg-blue-50 text-blue-600' : 'bg-emerald-50 text-emerald-600'
                      }`}>
                        {m.endpoints.length}
                      </span>
                    </span>
                  </button>
                ))}
              </div>
            </div>
          </div>

          {/* Main Content */}
          <div className="flex-1 min-w-0">
            {search && (
              <p className="text-sm text-gray-500 mb-4">
                {filteredTotal} Treffer in {filteredModules.length} Modulen
              </p>
            )}

            <div className="space-y-3">
              {filteredModules.map((m) => {
                const isExpanded = expandedModules.has(m.id)
                return (
                  <div
                    key={m.id}
                    ref={(el) => { moduleRefs.current[m.id] = el }}
                    className="bg-white rounded-lg border border-gray-200 overflow-hidden"
                  >
                    {/* Module Header */}
                    <button
                      onClick={() => toggleModule(m.id)}
                      className="w-full flex items-center justify-between px-4 py-3 hover:bg-gray-50 transition-colors"
                    >
                      <div className="flex items-center gap-3 min-w-0">
                        <svg
                          className={`w-4 h-4 text-gray-400 flex-shrink-0 transition-transform ${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={`text-[10px] font-mono font-bold px-2 py-0.5 rounded ${
                          m.service === 'python' ? 'bg-blue-50 text-blue-700' : 'bg-emerald-50 text-emerald-700'
                        }`}>
                          {m.service === 'python' ? 'PY' : 'GO'}
                        </span>
                        <ExposureBadge exposure={m.exposure} />
                        <span className="text-sm font-medium text-gray-900 truncate">{m.name}</span>
                      </div>
                      <div className="flex items-center gap-2 flex-shrink-0 ml-3">
                        <span className="text-xs text-gray-400 font-mono">{m.basePath}</span>
                        <span className="text-xs bg-gray-100 text-gray-600 px-2 py-0.5 rounded-full">
                          {m.endpoints.length}
                        </span>
                      </div>
                    </button>

                    {/* Endpoints Table */}
                    {isExpanded && (
                      <div className="border-t border-gray-100">
                        <table className="w-full">
                          <thead>
                            <tr className="bg-gray-50 text-xs text-gray-500">
                              <th className="text-left px-4 py-2 w-20">Methode</th>
                              <th className="text-left px-4 py-2">Pfad</th>
                              <th className="text-left px-4 py-2">Beschreibung</th>
                              <th className="text-left px-4 py-2 w-24">Exposure</th>
                            </tr>
                          </thead>
                          <tbody>
                            {m.endpoints.map((e, i) => {
                              const endpointExposure = e.exposure || m.exposure
                              const hasOverride = e.exposure && e.exposure !== m.exposure
                              return (
                                <tr
                                  key={`${e.method}-${e.path}-${i}`}
                                  className="border-t border-gray-50 hover:bg-gray-50/50 transition-colors"
                                >
                                  <td className="px-4 py-2">
                                    <span className={`inline-block text-[11px] font-mono font-bold px-2 py-0.5 rounded ${METHOD_COLORS[e.method]}`}>
                                      {e.method}
                                    </span>
                                  </td>
                                  <td className="px-4 py-2 font-mono text-xs text-gray-800">
                                    {e.path}
                                  </td>
                                  <td className="px-4 py-2 text-xs text-gray-600">
                                    {e.description}
                                  </td>
                                  <td className="px-4 py-2">
                                    {hasOverride ? (
                                      <ExposureBadge exposure={endpointExposure} />
                                    ) : (
                                      <span className="text-[10px] text-gray-300">—</span>
                                    )}
                                  </td>
                                </tr>
                              )
                            })}
                          </tbody>
                        </table>
                      </div>
                    )}
                  </div>
                )
              })}
            </div>

            {filteredModules.length === 0 && (
              <div className="text-center py-12 text-gray-400">
                <svg className="w-12 h-12 mx-auto mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                </svg>
                <p className="text-sm">Keine Endpoints gefunden</p>
                <p className="text-xs mt-1">Suchbegriff oder Filter anpassen</p>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  )
}
