import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Brain } from 'lucide-react'
import dayjs from 'dayjs'
import 'dayjs/locale/de'
import { api } from '../../utils/api'
import Markdown from '../../utils/Markdown'

dayjs.locale('de')

export default function AiPipelineInsightWidget({ refreshTick = 0 }) {
  const nav = useNavigate()
  const [insights, setInsights] = useState([])
  const [showInsight, setShowInsight] = useState(false)
  const [pipelineLoading, setPipelineLoading] = useState(false)
  const [pipelineError, setPipelineError] = useState(null)

  const load = () =>
    api.latestInsights().then((ins) => setInsights(Array.isArray(ins) ? ins : [])).catch(() => setInsights([]))

  useEffect(() => {
    load()
  }, [refreshTick])

  const runPipeline = async () => {
    setPipelineLoading(true)
    setPipelineError(null)
    try {
      await api.insightPipeline()
      await load()
    } catch (e) {
      setPipelineError(`Fehler: ${e.message}`)
    } finally {
      setPipelineLoading(false)
    }
  }

  const latestInsight = insights.find((i) => i.scope === 'gesamt') || insights[0]

  return (
    <div className="card section-gap" style={{ marginBottom: 16 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
        <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text1)' }}>KI-Auswertung</div>
        <button type="button" className="btn btn-secondary" style={{ fontSize: 11, padding: '4px 10px' }} onClick={() => nav('/analysis')}>
          <Brain size={11} /> Analysen →
        </button>
      </div>
      <button type="button" className="btn btn-primary btn-full" style={{ marginBottom: 10 }} onClick={runPipeline} disabled={pipelineLoading}>
        {pipelineLoading ? (
          <>
            <div className="spinner" style={{ width: 13, height: 13 }} /> Analyse läuft… (3 Stufen)
          </>
        ) : (
          <>
            <Brain size={13} /> 🔬 Mehrstufige Analyse starten
          </>
        )}
      </button>
      {pipelineError && <div style={{ fontSize: 12, color: '#D85A30', marginBottom: 8 }}>{pipelineError}</div>}

      {latestInsight ? (
        <>
          <div style={{ fontSize: 11, color: 'var(--text3)', marginBottom: 6 }}>
            Letzte Analyse: {dayjs(latestInsight.created).format('DD. MMMM YYYY, HH:mm')}
          </div>
          <div style={{ maxHeight: showInsight ? 'none' : 120, overflow: 'hidden', position: 'relative' }}>
            <Markdown text={latestInsight.content} />
            {!showInsight && (
              <div
                style={{
                  position: 'absolute',
                  bottom: 0,
                  left: 0,
                  right: 0,
                  height: 40,
                  background: 'linear-gradient(transparent,var(--surface))',
                }}
              />
            )}
          </div>
          <button
            type="button"
            style={{
              background: 'none',
              border: 'none',
              cursor: 'pointer',
              fontSize: 12,
              color: 'var(--accent)',
              marginTop: 6,
              padding: 0,
            }}
            onClick={() => setShowInsight((s) => !s)}
          >
            {showInsight ? '▲ Weniger anzeigen' : '▼ Vollständig anzeigen'}
          </button>
        </>
      ) : (
        <div style={{ fontSize: 13, color: 'var(--text3)', padding: '8px 0' }}>
          Noch keine KI-Auswertung vorhanden.
          <button type="button" className="btn btn-primary" style={{ marginTop: 8, display: 'block', fontSize: 12 }} onClick={() => nav('/analysis')}>
            Erste Analyse erstellen
          </button>
        </div>
      )}
    </div>
  )
}
