'use client'

import {
  Shield, Search, ChevronRight, Filter, Lock,
  BookOpen, Plus, Zap, BarChart3,
} from 'lucide-react'
import type { CanonicalControl, Framework } from '../_types'
import { SeverityBadge, StateBadge, LicenseRuleBadge } from './Badges'

export function ControlListView({
  controls,
  filteredControls,
  frameworks,
  searchQuery,
  setSearchQuery,
  severityFilter,
  setSeverityFilter,
  domainFilter,
  setDomainFilter,
  stateFilter,
  setStateFilter,
  domains,
  showStats,
  toggleStats,
  processedStats,
  onOpenGenerator,
  onCreate,
  onSelect,
}: {
  controls: CanonicalControl[]
  filteredControls: CanonicalControl[]
  frameworks: Framework[]
  searchQuery: string
  setSearchQuery: (v: string) => void
  severityFilter: string
  setSeverityFilter: (v: string) => void
  domainFilter: string
  setDomainFilter: (v: string) => void
  stateFilter: string
  setStateFilter: (v: string) => void
  domains: string[]
  showStats: boolean
  toggleStats: () => void
  processedStats: Array<Record<string, unknown>>
  onOpenGenerator: () => void
  onCreate: () => void
  onSelect: (ctrl: CanonicalControl) => void
}) {
  return (
    <div className="flex flex-col h-full">
      {/* Header */}
      <div className="border-b border-gray-200 bg-white px-6 py-4">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-3">
            <Shield className="w-6 h-6 text-purple-600" />
            <div>
              <h1 className="text-lg font-semibold text-gray-900">Canonical Control Library</h1>
              <p className="text-xs text-gray-500">
                {controls.length} unabhaengig formulierte Security Controls —{' '}
                {controls.reduce((sum, c) => sum + c.open_anchors.length, 0)} Open-Source-Referenzen
              </p>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <button
              onClick={toggleStats}
              className="flex items-center gap-1.5 px-3 py-2 text-sm text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50"
            >
              <BarChart3 className="w-4 h-4" />
              Stats
            </button>
            <button
              onClick={onOpenGenerator}
              className="flex items-center gap-1.5 px-3 py-2 text-sm text-white bg-amber-600 rounded-lg hover:bg-amber-700"
            >
              <Zap className="w-4 h-4" />
              Generator
            </button>
            <button
              onClick={onCreate}
              className="flex items-center gap-1.5 px-3 py-2 text-sm text-white bg-purple-600 rounded-lg hover:bg-purple-700"
            >
              <Plus className="w-4 h-4" />
              Neues Control
            </button>
          </div>
        </div>

        {/* Frameworks */}
        {frameworks.length > 0 && (
          <div className="mb-4 p-3 bg-purple-50 rounded-lg">
            <div className="flex items-center gap-2 text-xs text-purple-700">
              <Lock className="w-3 h-3" />
              <span className="font-medium">{frameworks[0]?.name} v{frameworks[0]?.version}</span>
              <span className="text-purple-500">—</span>
              <span>{frameworks[0]?.description}</span>
            </div>
          </div>
        )}

        {/* Filters */}
        <div className="flex items-center gap-3">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
            <input
              type="text"
              placeholder="Controls durchsuchen..."
              value={searchQuery}
              onChange={e => setSearchQuery(e.target.value)}
              className="w-full pl-9 pr-4 py-2 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500"
            />
          </div>
          <div className="flex items-center gap-1">
            <Filter className="w-4 h-4 text-gray-400" />
          </div>
          <select
            value={severityFilter}
            onChange={e => setSeverityFilter(e.target.value)}
            className="text-sm border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-purple-500"
          >
            <option value="">Alle Schweregrade</option>
            <option value="critical">Kritisch</option>
            <option value="high">Hoch</option>
            <option value="medium">Mittel</option>
            <option value="low">Niedrig</option>
          </select>
          <select
            value={domainFilter}
            onChange={e => setDomainFilter(e.target.value)}
            className="text-sm border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-purple-500"
          >
            <option value="">Alle Domains</option>
            {domains.map(d => (
              <option key={d} value={d}>{d}</option>
            ))}
          </select>
          <select
            value={stateFilter}
            onChange={e => setStateFilter(e.target.value)}
            className="text-sm border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-purple-500"
          >
            <option value="">Alle Status</option>
            <option value="draft">Draft</option>
            <option value="approved">Approved</option>
            <option value="needs_review">Review noetig</option>
            <option value="too_close">Zu aehnlich</option>
            <option value="duplicate">Duplikat</option>
          </select>
        </div>

        {/* Processing Stats */}
        {showStats && processedStats.length > 0 && (
          <div className="mt-3 p-3 bg-gray-50 rounded-lg">
            <h4 className="text-xs font-semibold text-gray-700 mb-2">Verarbeitungsfortschritt</h4>
            <div className="grid grid-cols-3 gap-3">
              {processedStats.map((s, i) => (
                <div key={i} className="text-xs">
                  <span className="font-medium text-gray-700">{String(s.collection)}</span>
                  <div className="flex gap-2 mt-1 text-gray-500">
                    <span>{String(s.processed_chunks)} verarbeitet</span>
                    <span>{String(s.direct_adopted)} direkt</span>
                    <span>{String(s.llm_reformed)} reformuliert</span>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>

      {/* Control List */}
      <div className="flex-1 overflow-y-auto p-6">
        <div className="space-y-3">
          {filteredControls.map(ctrl => (
            <button
              key={ctrl.control_id}
              onClick={() => onSelect(ctrl)}
              className="w-full text-left bg-white border border-gray-200 rounded-lg p-4 hover:border-purple-300 hover:shadow-sm transition-all group"
            >
              <div className="flex items-start justify-between">
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 mb-1">
                    <span className="text-xs font-mono text-purple-600 bg-purple-50 px-1.5 py-0.5 rounded">{ctrl.control_id}</span>
                    <SeverityBadge severity={ctrl.severity} />
                    <StateBadge state={ctrl.release_state} />
                    <LicenseRuleBadge rule={ctrl.license_rule} />
                    {ctrl.risk_score !== null && (
                      <span className="text-xs text-gray-400">Score: {ctrl.risk_score}</span>
                    )}
                  </div>
                  <h3 className="text-sm font-medium text-gray-900 group-hover:text-purple-700">{ctrl.title}</h3>
                  <p className="text-xs text-gray-500 mt-1 line-clamp-2">{ctrl.objective}</p>

                  {/* Open anchors summary */}
                  <div className="flex items-center gap-2 mt-2">
                    <BookOpen className="w-3 h-3 text-green-600" />
                    <span className="text-xs text-green-700">
                      {ctrl.open_anchors.length} Open-Source-Referenzen:
                    </span>
                    <span className="text-xs text-gray-500">
                      {ctrl.open_anchors.map(a => a.framework).filter((v, i, arr) => arr.indexOf(v) === i).join(', ')}
                    </span>
                  </div>
                </div>
                <ChevronRight className="w-4 h-4 text-gray-300 group-hover:text-purple-500 flex-shrink-0 mt-1 ml-4" />
              </div>
            </button>
          ))}

          {filteredControls.length === 0 && (
            <div className="text-center py-12 text-gray-400 text-sm">
              {controls.length === 0
                ? 'Noch keine Controls vorhanden. Klicke auf "Neues Control" um zu starten.'
                : 'Keine Controls gefunden.'}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
