'use client'

import { useState, useMemo, useCallback } from 'react'
import { useSDK } from '@/lib/sdk'
import {
  Database,
  Search,
  Plus,
  ChevronDown,
  ChevronRight,
  BarChart3,
  Layers,
  Users,
  Settings,
} from 'lucide-react'
import type {
  CatalogId,
  CatalogModule,
  CatalogEntry,
  CatalogMeta,
  CustomCatalogEntry,
} from '@/lib/sdk/catalog-manager/types'
import { CATALOG_MODULE_LABELS } from '@/lib/sdk/catalog-manager/types'
import {
  CATALOG_REGISTRY,
  getAllEntries,
  getCatalogsByModule,
  getOverviewStats,
  searchCatalog,
} from '@/lib/sdk/catalog-manager/catalog-registry'
import CatalogModuleTabs from '@/components/catalog-manager/CatalogModuleTabs'
import CatalogTable from '@/components/catalog-manager/CatalogTable'
import CatalogEntryForm from '@/components/catalog-manager/CatalogEntryForm'

// =============================================================================
// STAT CARD COMPONENT
// =============================================================================

interface StatCardProps {
  icon: React.ReactNode
  label: string
  value: number
  color: 'violet' | 'blue' | 'emerald' | 'amber'
}

const colorMap = {
  violet: {
    bg: 'bg-violet-50 dark:bg-violet-900/20',
    text: 'text-violet-600 dark:text-violet-400',
  },
  blue: {
    bg: 'bg-blue-50 dark:bg-blue-900/20',
    text: 'text-blue-600 dark:text-blue-400',
  },
  emerald: {
    bg: 'bg-emerald-50 dark:bg-emerald-900/20',
    text: 'text-emerald-600 dark:text-emerald-400',
  },
  amber: {
    bg: 'bg-amber-50 dark:bg-amber-900/20',
    text: 'text-amber-600 dark:text-amber-400',
  },
}

function StatCard({ icon, label, value, color }: StatCardProps) {
  const colors = colorMap[color]
  return (
    <div className={`flex items-center gap-3 px-4 py-3 rounded-xl ${colors.bg}`}>
      <div className={colors.text}>{icon}</div>
      <div>
        <p className="text-xs text-gray-500 dark:text-gray-400">{label}</p>
        <p className={`text-lg font-bold ${colors.text}`}>{value.toLocaleString('de-DE')}</p>
      </div>
    </div>
  )
}

// =============================================================================
// MAIN CONTENT COMPONENT
// =============================================================================

export function CatalogManagerContent() {
  const { state, dispatch } = useSDK()
  const customCatalogs = state.customCatalogs ?? {}

  // UI State
  const [activeModule, setActiveModule] = useState<CatalogModule | 'all'>('all')
  const [selectedCatalogId, setSelectedCatalogId] = useState<CatalogId | null>(null)
  const [searchQuery, setSearchQuery] = useState('')
  const [expandedCatalogs, setExpandedCatalogs] = useState<Set<CatalogId>>(new Set())
  const [formState, setFormState] = useState<{
    open: boolean
    catalog: CatalogMeta | null
    entry: CatalogEntry | null
  }>({ open: false, catalog: null, entry: null })

  // Computed data
  const overviewStats = useMemo(() => getOverviewStats(customCatalogs), [customCatalogs])

  const visibleCatalogs = useMemo(() => {
    if (activeModule === 'all') {
      return Object.values(CATALOG_REGISTRY)
    }
    return getCatalogsByModule(activeModule)
  }, [activeModule])

  const selectedCatalog = selectedCatalogId ? CATALOG_REGISTRY[selectedCatalogId] : null

  const catalogEntries = useMemo(() => {
    if (!selectedCatalogId) return []
    const custom = customCatalogs[selectedCatalogId] || []
    if (searchQuery.trim()) {
      return searchCatalog(selectedCatalogId, searchQuery, custom)
    }
    return getAllEntries(selectedCatalogId, custom)
  }, [selectedCatalogId, customCatalogs, searchQuery])

  // Handlers
  const toggleCatalogExpand = useCallback((id: CatalogId) => {
    setExpandedCatalogs(prev => {
      const next = new Set(prev)
      if (next.has(id)) {
        next.delete(id)
      } else {
        next.add(id)
      }
      return next
    })
  }, [])

  const handleSelectCatalog = useCallback((id: CatalogId) => {
    setSelectedCatalogId(id)
    setSearchQuery('')
  }, [])

  const handleAddEntry = useCallback((catalog: CatalogMeta) => {
    setFormState({ open: true, catalog, entry: null })
  }, [])

  const handleEditEntry = useCallback((catalog: CatalogMeta, entry: CatalogEntry) => {
    setFormState({ open: true, catalog, entry })
  }, [])

  const handleCloseForm = useCallback(() => {
    setFormState({ open: false, catalog: null, entry: null })
  }, [])

  const handleSaveEntry = useCallback((data: Record<string, unknown>) => {
    if (!formState.catalog) return

    if (formState.entry && formState.entry.source === 'custom') {
      // Update existing custom entry
      dispatch({
        type: 'UPDATE_CUSTOM_CATALOG_ENTRY',
        payload: {
          catalogId: formState.catalog.id,
          entryId: formState.entry.id,
          data,
        },
      })
    } else {
      // Create new custom entry
      const newEntry: CustomCatalogEntry = {
        id: crypto.randomUUID(),
        catalogId: formState.catalog.id,
        data,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      }
      dispatch({
        type: 'ADD_CUSTOM_CATALOG_ENTRY',
        payload: newEntry,
      })
    }

    handleCloseForm()
  }, [formState, dispatch, handleCloseForm])

  const handleDeleteEntry = useCallback((catalogId: CatalogId, entryId: string) => {
    dispatch({
      type: 'DELETE_CUSTOM_CATALOG_ENTRY',
      payload: { catalogId, entryId },
    })
  }, [dispatch])

  // =============================================================================
  // RENDER
  // =============================================================================

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900">
      {/* Header */}
      <div className="bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700">
        <div className="max-w-7xl mx-auto px-6 py-6">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-4">
              <div className="p-3 bg-violet-100 dark:bg-violet-900/30 rounded-xl">
                <Database className="h-6 w-6 text-violet-600 dark:text-violet-400" />
              </div>
              <div>
                <h1 className="text-2xl font-bold text-gray-900 dark:text-white">
                  Katalogverwaltung
                </h1>
                <p className="text-sm text-gray-500 dark:text-gray-400 mt-0.5">
                  Alle SDK-Kataloge und Auswahltabellen zentral verwalten
                </p>
              </div>
            </div>
          </div>

          {/* Stats Bar */}
          <div className="grid grid-cols-4 gap-4 mt-6">
            <StatCard
              icon={<Layers className="h-5 w-5" />}
              label="Kataloge"
              value={overviewStats.totalCatalogs}
              color="violet"
            />
            <StatCard
              icon={<Database className="h-5 w-5" />}
              label="System-Eintraege"
              value={overviewStats.totalSystemEntries}
              color="blue"
            />
            <StatCard
              icon={<Users className="h-5 w-5" />}
              label="Eigene Eintraege"
              value={overviewStats.totalCustomEntries}
              color="emerald"
            />
            <StatCard
              icon={<BarChart3 className="h-5 w-5" />}
              label="Gesamt"
              value={overviewStats.totalEntries}
              color="amber"
            />
          </div>
        </div>
      </div>

      {/* Module Tabs */}
      <div className="max-w-7xl mx-auto px-6 mt-6">
        <CatalogModuleTabs
          activeModule={activeModule}
          onModuleChange={setActiveModule}
          stats={overviewStats}
        />
      </div>

      {/* Content Area */}
      <div className="max-w-7xl mx-auto px-6 py-6">
        <div className="grid grid-cols-12 gap-6">
          {/* Left: Catalog List */}
          <div className="col-span-4">
            <div className="bg-white dark:bg-gray-800 rounded-xl shadow border border-gray-200 dark:border-gray-700 overflow-hidden">
              <div className="px-4 py-3 border-b border-gray-200 dark:border-gray-700">
                <h2 className="text-sm font-semibold text-gray-700 dark:text-gray-300">
                  {activeModule === 'all'
                    ? 'Alle Kataloge'
                    : CATALOG_MODULE_LABELS[activeModule]}
                  <span className="ml-2 text-gray-400 font-normal">
                    ({visibleCatalogs.length})
                  </span>
                </h2>
              </div>

              <div className="divide-y divide-gray-100 dark:divide-gray-700/50 max-h-[calc(100vh-400px)] overflow-y-auto">
                {visibleCatalogs.map(catalog => {
                  const customCount = customCatalogs[catalog.id]?.length ?? 0
                  const isSelected = selectedCatalogId === catalog.id

                  return (
                    <button
                      key={catalog.id}
                      onClick={() => handleSelectCatalog(catalog.id)}
                      className={`w-full text-left px-4 py-3 transition-colors ${
                        isSelected
                          ? 'bg-violet-50 dark:bg-violet-900/20 border-l-3 border-l-violet-600'
                          : 'hover:bg-gray-50 dark:hover:bg-gray-700/50'
                      }`}
                    >
                      <div className="flex items-center justify-between">
                        <div className="min-w-0">
                          <p className={`text-sm font-medium truncate ${
                            isSelected
                              ? 'text-violet-700 dark:text-violet-300'
                              : 'text-gray-900 dark:text-white'
                          }`}>
                            {catalog.name}
                          </p>
                          <p className="text-xs text-gray-500 dark:text-gray-400 mt-0.5 truncate">
                            {catalog.description}
                          </p>
                        </div>
                        <div className="flex items-center gap-2 ml-2 shrink-0">
                          <span className="inline-flex items-center px-2 py-0.5 text-xs font-medium rounded-full bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400">
                            {catalog.systemCount}
                          </span>
                          {customCount > 0 && (
                            <span className="inline-flex items-center px-2 py-0.5 text-xs font-medium rounded-full bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400">
                              +{customCount}
                            </span>
                          )}
                        </div>
                      </div>
                    </button>
                  )
                })}
              </div>
            </div>
          </div>

          {/* Right: Catalog Detail / Table */}
          <div className="col-span-8">
            {selectedCatalog ? (
              <div className="bg-white dark:bg-gray-800 rounded-xl shadow border border-gray-200 dark:border-gray-700 overflow-hidden">
                {/* Catalog Header */}
                <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
                  <div className="flex items-center justify-between">
                    <div>
                      <h2 className="text-lg font-semibold text-gray-900 dark:text-white">
                        {selectedCatalog.name}
                      </h2>
                      <p className="text-sm text-gray-500 dark:text-gray-400 mt-0.5">
                        {selectedCatalog.description}
                      </p>
                    </div>
                    <div className="flex items-center gap-2">
                      <span className="text-xs text-gray-500 dark:text-gray-400">
                        {CATALOG_MODULE_LABELS[selectedCatalog.module]}
                      </span>
                      {selectedCatalog.allowCustom && (
                        <span className="inline-flex items-center px-2 py-0.5 text-xs font-medium rounded-full bg-emerald-100 dark:bg-emerald-900/30 text-emerald-700 dark:text-emerald-400">
                          Erweiterbar
                        </span>
                      )}
                    </div>
                  </div>
                </div>

                {/* Table */}
                <CatalogTable
                  catalog={selectedCatalog}
                  entries={catalogEntries}
                  searchQuery={searchQuery}
                  onSearchChange={setSearchQuery}
                  onEditCustomEntry={(entry) => handleEditEntry(selectedCatalog, entry)}
                  onDeleteCustomEntry={(entryId) => handleDeleteEntry(selectedCatalog.id, entryId)}
                  onAddEntry={() => handleAddEntry(selectedCatalog)}
                />
              </div>
            ) : (
              /* Empty State */
              <div className="bg-white dark:bg-gray-800 rounded-xl shadow border border-gray-200 dark:border-gray-700 p-12">
                <div className="text-center">
                  <Settings className="h-12 w-12 text-gray-300 dark:text-gray-600 mx-auto mb-4" />
                  <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">
                    Katalog auswaehlen
                  </h3>
                  <p className="text-sm text-gray-500 dark:text-gray-400 max-w-sm mx-auto">
                    Waehlen Sie einen Katalog aus der Liste links, um dessen Eintraege anzuzeigen und zu verwalten.
                  </p>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Form Modal */}
      {formState.open && formState.catalog && (
        <CatalogEntryForm
          catalog={formState.catalog}
          entry={formState.entry}
          onSave={handleSaveEntry}
          onCancel={handleCloseForm}
        />
      )}
    </div>
  )
}
