'use client'

import { useState, useEffect } from 'react'

interface NormRef {
  id: string
  number: string
  title_de: string
  norm_type: string
  scope_de: string
  mandatory: boolean
}

interface NormSuggestion {
  norm: NormRef
  reason: string
  confidence: number
}

interface NormResult {
  a_norms: NormSuggestion[]
  b1_norms: NormSuggestion[]
  b2_norms: NormSuggestion[]
  c_norms: NormSuggestion[]
  total: number
}

const TYPE_CONFIG: Record<string, { label: string; color: string; desc: string }> = {
  a_norms: { label: 'A-Normen', color: 'border-red-200 bg-red-50 text-red-800', desc: 'Grundnormen (immer anwendbar)' },
  b1_norms: { label: 'B1-Normen', color: 'border-blue-200 bg-blue-50 text-blue-800', desc: 'Sicherheitsgrundnormen' },
  b2_norms: { label: 'B2-Normen', color: 'border-green-200 bg-green-50 text-green-800', desc: 'Sicherheitsfachgrundnormen' },
  c_norms: { label: 'C-Normen', color: 'border-purple-200 bg-purple-50 text-purple-800', desc: 'Maschinenspezifische Normen' },
}

export function SuggestedNorms({ projectId }: { projectId: string }) {
  const [data, setData] = useState<NormResult | null>(null)
  const [loading, setLoading] = useState(true)
  const [collapsed, setCollapsed] = useState(false)
  const [customNorms, setCustomNorms] = useState<Array<{ number: string; title: string }>>([])
  const [customNormNumber, setCustomNormNumber] = useState('')
  const [customNormTitle, setCustomNormTitle] = useState('')

  useEffect(() => {
    fetch(`/api/sdk/v1/iace/projects/${projectId}/suggested-norms`)
      .then((r) => r.ok ? r.json() : null)
      .then((json) => {
        if (json?.suggestions) setData(json.suggestions)
        else if (json?.a_norms !== undefined) setData(json)
      })
      .catch(() => {})
      .finally(() => setLoading(false))
  }, [projectId])

  if (loading) return null
  if (!data || data.total === 0) return null

  return (
    <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700">
      <button
        onClick={() => setCollapsed(!collapsed)}
        className="w-full flex items-center justify-between p-6 text-left"
      >
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 bg-amber-50 rounded-lg flex items-center justify-center">
            <svg className="w-5 h-5 text-amber-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253" />
            </svg>
          </div>
          <div>
            <h2 className="text-sm font-semibold text-gray-900 dark:text-white">
              Normenrecherche — {data.total} relevante Normen
            </h2>
            <p className="text-xs text-gray-500">
              Automatisch ermittelt aus Maschinentyp, Gefaehrdungen und Komponenten
            </p>
          </div>
        </div>
        <div className="w-8 h-8 flex items-center justify-center rounded-full hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors flex-shrink-0">
          <svg className={`w-5 h-5 text-gray-400 transition-transform ${collapsed ? '' : 'rotate-180'}`} fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
          </svg>
        </div>
      </button>

      {!collapsed && (
        <div className="px-6 pb-6 space-y-4">
          {/* Legend */}
          <div className="flex flex-wrap gap-2 text-xs">
            {Object.entries(TYPE_CONFIG).map(([key, cfg]) => (
              <span key={key} className={`px-2 py-0.5 rounded border ${cfg.color}`}>{cfg.label}: {cfg.desc}</span>
            ))}
          </div>

          {/* Norm groups */}
          {(['a_norms', 'b1_norms', 'b2_norms', 'c_norms'] as const).map((type) => {
            const norms = data[type]
            if (!norms || norms.length === 0) return null
            const cfg = TYPE_CONFIG[type]
            return (
              <div key={type}>
                <h3 className={`text-xs font-semibold px-2 py-1 rounded inline-block mb-2 border ${cfg.color}`}>
                  {cfg.label} ({norms.length})
                </h3>
                <div className="space-y-2">
                  {norms.map((s) => (
                    <div key={s.norm.id} className="flex items-start gap-3 p-3 rounded-lg bg-gray-50 dark:bg-gray-700/50 border border-gray-100 dark:border-gray-600">
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2">
                          <span className="text-sm font-mono font-semibold text-gray-900 dark:text-white">
                            {s.norm.number}
                          </span>
                          {s.norm.mandatory && (
                            <span className="px-1.5 py-0.5 text-xs font-medium bg-red-100 text-red-700 rounded">
                              Pflicht
                            </span>
                          )}
                          <span className="px-1.5 py-0.5 text-xs bg-gray-200 text-gray-600 rounded">
                            {Math.round(s.confidence * 100)}%
                          </span>
                        </div>
                        <p className="text-xs text-gray-700 dark:text-gray-300 mt-0.5">{s.norm.title_de}</p>
                        <p className="text-xs text-gray-500 mt-1">{s.norm.scope_de}</p>
                        <p className="text-xs text-amber-600 mt-1">
                          Grund: {s.reason}
                        </p>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )
          })}

          {/* Add custom norm */}
          <div className="p-3 rounded-lg bg-gray-50 dark:bg-gray-700/50 border border-gray-200 dark:border-gray-600">
            <p className="text-xs font-medium text-gray-700 dark:text-gray-300 mb-2">Weitere Norm ergaenzen</p>
            <div className="flex gap-2">
              <input
                type="text" placeholder="z.B. ISO 13857:2019"
                value={customNormNumber} onChange={(e) => setCustomNormNumber(e.target.value)}
                className="flex-1 px-3 py-1.5 text-xs border border-gray-300 rounded-lg focus:ring-1 focus:ring-purple-400 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
              />
              <input
                type="text" placeholder="Titel (optional)"
                value={customNormTitle} onChange={(e) => setCustomNormTitle(e.target.value)}
                className="flex-1 px-3 py-1.5 text-xs border border-gray-300 rounded-lg focus:ring-1 focus:ring-purple-400 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
              />
              <button
                onClick={() => {
                  if (customNormNumber.trim()) {
                    setCustomNorms((prev) => [...prev, { number: customNormNumber.trim(), title: customNormTitle.trim() }])
                    setCustomNormNumber('')
                    setCustomNormTitle('')
                  }
                }}
                disabled={!customNormNumber.trim()}
                className="px-3 py-1.5 text-xs bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:bg-gray-300 disabled:cursor-not-allowed transition-colors"
              >
                + Hinzufuegen
              </button>
            </div>
            {customNorms.length > 0 && (
              <div className="mt-2 space-y-1">
                {customNorms.map((cn, i) => (
                  <div key={i} className="flex items-center gap-2 text-xs">
                    <span className="font-mono font-semibold text-gray-800 dark:text-gray-200">{cn.number}</span>
                    {cn.title && <span className="text-gray-500">— {cn.title}</span>}
                    <span className="px-1.5 py-0.5 bg-blue-100 text-blue-700 rounded text-xs">Manuell</span>
                    <button onClick={() => setCustomNorms((prev) => prev.filter((_, j) => j !== i))} className="text-red-400 hover:text-red-600">
                      <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" /></svg>
                    </button>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* Pflicht-Erklärung + Disclaimer */}
          <div className="space-y-2 text-xs">
            <div className="p-3 rounded-lg bg-red-50 border border-red-200 text-red-800">
              <strong>Pflicht</strong> bedeutet: Diese Norm ist fuer diesen Maschinentyp typischerweise zwingend anzuwenden
              (z.B. ISO 12100 fuer alle Maschinen, EN 692 fuer mechanische Pressen). Die Anwendung harmonisierter Normen
              erzeugt eine Konformitaetsvermutung.
            </div>
            <div className="p-3 rounded-lg bg-amber-50 border border-amber-200 text-amber-800">
              <strong>Hinweis:</strong> Diese Normenvorschlaege basieren auf dem Maschinentyp und den identifizierten
              Gefaehrdungen. Der CE-Fachmann muss die Anwendbarkeit pruefen und ggf. weitere Normen ueber das Feld oben ergaenzen.
              Normtexte muessen separat beschafft werden (z.B. ueber <a href="https://www.beuth.de" target="_blank" rel="noopener noreferrer" className="underline font-medium">beuth.de</a>).
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
