'use client'

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

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

function catBadge(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'
  return 'bg-blue-100 text-blue-800'
}

interface Props {
  projectId: string
  mitigationId: string
}

export function MitigationHints({ projectId, mitigationId }: Props) {
  const [hints, setHints] = useState<Hint[]>([])
  const [loading, setLoading] = useState(false)
  const [loaded, setLoaded] = useState(false)

  const load = useCallback(async () => {
    setLoading(true)
    try {
      const res = await fetch(`/api/sdk/v1/iace/projects/${projectId}/mitigations/${mitigationId}/regulatory-hints`)
      if (res.ok) {
        const data = await res.json()
        setHints(data.hints || [])
      }
    } catch { /* ignore */ }
    finally { setLoading(false); setLoaded(true) }
  }, [projectId, mitigationId])

  if (!loaded) {
    return (
      <button onClick={load} disabled={loading}
        className="inline-flex items-center gap-1 text-[10px] text-purple-600 hover:text-purple-800 disabled:opacity-50">
        {loading ? 'Lade...' : 'TRBS/OSHA Hinweise laden'}
      </button>
    )
  }

  if (hints.length === 0) return <span className="text-[10px] text-gray-400">Keine Hinweise</span>

  return (
    <div className="space-y-1.5 mt-1">
      <p className="text-[10px] font-medium text-gray-500">Regulatorische Hinweise:</p>
      {hints.map((h, i) => (
        <div key={i} className="p-2 rounded border border-gray-200 dark:border-gray-600 bg-white dark:bg-gray-800 text-[11px]">
          <span className={`inline-flex px-1 py-0.5 rounded text-[9px] font-medium ${catBadge(h.category)}`}>
            {h.regulation_short || h.regulation_id}
          </span>
          {h.pages?.length ? <span className="text-gray-400 ml-1">S.{h.pages.join(',')}</span> : null}
          <p className="text-gray-600 dark:text-gray-300 mt-0.5 leading-relaxed">{h.text}</p>
        </div>
      ))}
    </div>
  )
}
