'use client'

import React, { useState, useCallback } from 'react'

interface RegulatoryHint {
  regulation_id: string
  regulation_short: string
  category: string
  text: string
  pages?: number[]
  source_url?: string
  score: number
}

interface Props {
  projectId: string
  hazardId: string
  hazardName: string
}

function categoryBadge(cat: string): string {
  if (cat === 'trbs') return 'bg-orange-100 text-orange-800'
  if (cat === 'trgs') return 'bg-red-100 text-red-800'
  if (cat === 'asr') return 'bg-teal-100 text-teal-800'
  if (cat === 'osha' || cat.startsWith('ce_')) return 'bg-blue-100 text-blue-800'
  return 'bg-gray-100 text-gray-700'
}

export function RegulatoryHintsPanel({ projectId, hazardId, hazardName }: Props) {
  const [hints, setHints] = useState<RegulatoryHint[]>([])
  const [loading, setLoading] = useState(false)
  const [loaded, setLoaded] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const loadHints = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const res = await fetch(`/api/sdk/v1/iace/projects/${projectId}/hazards/${hazardId}/regulatory-hints`)
      if (!res.ok) {
        setError('Hinweise konnten nicht geladen werden')
        return
      }
      const data = await res.json()
      setHints(data.hints || [])
    } catch {
      setError('Verbindung zum RAG-Service fehlgeschlagen')
    } finally {
      setLoading(false)
      setLoaded(true)
    }
  }, [projectId, hazardId])

  if (!loaded) {
    return (
      <button
        onClick={loadHints}
        disabled={loading}
        className="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-purple-700 bg-purple-50 rounded-lg hover:bg-purple-100 dark:text-purple-300 dark:bg-purple-900/30 transition-colors disabled:opacity-50"
      >
        {loading ? (
          <>
            <span className="animate-spin inline-block w-3 h-3 border border-purple-400 border-t-transparent rounded-full" />
            Lade Hinweise...
          </>
        ) : (
          <>
            <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="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>
            TRBS/OSHA Hinweise laden
          </>
        )}
      </button>
    )
  }

  if (error) {
    return <p className="text-xs text-red-500">{error}</p>
  }

  if (hints.length === 0) {
    return <p className="text-xs text-gray-400">Keine regulatorischen Hinweise gefunden</p>
  }

  return (
    <div className="space-y-2 mt-2">
      <p className="text-xs font-medium text-gray-500 dark:text-gray-400">
        Regulatorische Hinweise ({hints.length})
      </p>
      {hints.map((hint, i) => (
        <div
          key={i}
          className="p-2.5 rounded-lg border border-gray-200 dark:border-gray-700 bg-gray-50/50 dark:bg-gray-800/50 text-xs space-y-1"
        >
          <div className="flex items-center gap-2 flex-wrap">
            <span className={`inline-flex px-1.5 py-0.5 rounded font-medium ${categoryBadge(hint.category)}`}>
              {hint.regulation_short || hint.regulation_id}
            </span>
            {hint.pages && hint.pages.length > 0 && (
              <span className="text-gray-400">S. {hint.pages.join(', ')}</span>
            )}
            <span className="text-gray-400 ml-auto">{(hint.score * 100).toFixed(0)}% Relevanz</span>
          </div>
          <p className="text-gray-700 dark:text-gray-300 leading-relaxed">{hint.text}</p>
          {hint.source_url && (
            <a
              href={hint.source_url}
              target="_blank"
              rel="noopener noreferrer"
              className="text-purple-600 hover:text-purple-800 dark:text-purple-400"
            >
              Quelle
              <svg className="w-3 h-3 inline-block ml-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
              </svg>
            </a>
          )}
        </div>
      ))}
    </div>
  )
}
