'use client'

import { useState, useMemo, useRef } from 'react'
import { apiModules } from '@/lib/sdk/api-docs/endpoints'
import type { HttpMethod, BackendService } 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',
}

type ServiceFilter = 'all' | BackendService

export default function ApiDocsPage() {
  const [search, setSearch] = useState('')
  const [serviceFilter, setServiceFilter] = useState<ServiceFilter>('all')
  const [methodFilter, setMethodFilter] = useState<HttpMethod | 'all'>('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)
      .map((m) => {
        const eps = m.endpoints.filter((e) => {
          if (methodFilter !== 'all' && e.method !== methodFilter) 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])

  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)
    return { total, python, go, modules: apiModules.length }
  }, [])

  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>

          {/* 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>

            {/* 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-[140px] max-h-[calc(100vh-180px)] 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"
                  >
                    <span className="truncate text-gray-700 group-hover:text-gray-900">
                      {m.id}
                    </span>
                    <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>
                  </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>
                        <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>
                            </tr>
                          </thead>
                          <tbody>
                            {m.endpoints.map((e, i) => (
                              <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>
                              </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>
  )
}
