'use client'

import React, { useState } from 'react'

export interface CheckItem {
  id: string
  label: string
  passed: boolean
  severity: string
  matched_text: string
  level?: number
  parent?: string | null
  skipped?: boolean
  hint?: string
}

export interface DocResult {
  label: string
  url: string
  doc_type: string
  word_count: number
  completeness_pct: number
  correctness_pct?: number
  checks: CheckItem[]
  findings_count: number
  error: string
  scenario?: string  // regenerate | fix | import | skip
}

export const SCENARIO_LABELS: Record<string, { label: string; color: string; bg: string }> = {
  regenerate: { label: 'Neugenerierung', color: 'text-red-700', bg: 'bg-red-100' },
  fix: { label: 'Korrekturen', color: 'text-amber-700', bg: 'bg-amber-100' },
  import: { label: 'Konform', color: 'text-green-700', bg: 'bg-green-100' },
  missing: { label: 'Fehlt', color: 'text-gray-600', bg: 'bg-gray-100' },
}

export const DOC_TYPE_LABELS: Record<string, string> = {
  dse: 'DSI', agb: 'AGB', impressum: 'Impressum',
  cookie: 'Cookie', widerruf: 'Widerruf', other: 'Sonstiges',
  social_media: 'Social Media', dsfa: 'DSFA', joint_controller: 'Art. 26',
  eu_institution: 'EU-Inst.', banner: 'Banner',
}

interface GroupedCheck {
  check: CheckItem
  children: CheckItem[]
}

export function groupChecks(checks: CheckItem[]): GroupedCheck[] {
  const l1 = checks.filter(c => (c.level ?? 1) === 1)
  return l1.map(c => ({
    check: c,
    children: checks.filter(ch => ch.parent === c.id && (ch.level ?? 1) === 2),
  }))
}

export function CheckIcon({ passed, skipped, isInfo }: { passed: boolean; skipped?: boolean; isInfo?: boolean }) {
  if (skipped) {
    return (
      <svg className="w-4 h-4 text-gray-300 mt-0.5 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 12H4" />
      </svg>
    )
  }
  if (passed) {
    return (
      <svg className="w-4 h-4 text-green-500 mt-0.5 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
      </svg>
    )
  }
  if (isInfo) {
    return (
      <svg className="w-4 h-4 text-gray-400 mt-0.5 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
      </svg>
    )
  }
  return (
    <svg className="w-4 h-4 text-red-500 mt-0.5 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
    </svg>
  )
}

function L2Summary({ children }: { children: CheckItem[] }) {
  const active = children.filter(c => !c.skipped)
  if (active.length === 0) return null
  const passed = active.filter(c => c.passed).length
  return (
    <span className="text-xs text-gray-400 ml-1">
      ({passed}/{active.length})
    </span>
  )
}

export function ChecklistView({ results }: { results: DocResult[] }) {
  const [expanded, setExpanded] = useState<number | null>(null)

  if (!results || results.length === 0) return null

  const scenarioCounts = {
    regenerate: results.filter(r => r.scenario === 'regenerate').length,
    fix: results.filter(r => r.scenario === 'fix').length,
    import: results.filter(r => r.scenario === 'import').length,
    missing: results.filter(r => r.scenario === 'missing').length,
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between flex-wrap gap-2">
        <h3 className="text-sm font-semibold text-gray-800">
          Dokumenten-Pruefung ({results.length} Dokumente)
        </h3>
        <div className="flex gap-2 text-[10px]">
          {scenarioCounts.import > 0 && <span className="bg-green-100 text-green-700 px-2 py-0.5 rounded-full">{scenarioCounts.import} konform</span>}
          {scenarioCounts.fix > 0 && <span className="bg-amber-100 text-amber-700 px-2 py-0.5 rounded-full">{scenarioCounts.fix} Korrekturen</span>}
          {scenarioCounts.regenerate > 0 && <span className="bg-red-100 text-red-700 px-2 py-0.5 rounded-full">{scenarioCounts.regenerate} Neugenerierung</span>}
          {scenarioCounts.missing > 0 && <span className="bg-gray-100 text-gray-600 px-2 py-0.5 rounded-full">{scenarioCounts.missing} fehlt</span>}
        </div>
      </div>

      <div className="space-y-2">
        {results.map((r, i) => {
          const isExp = expanded === i
          const pct = r.completeness_pct
          const cpct = r.correctness_pct ?? 0
          const barColor = pct === 100 ? 'bg-green-500' : pct >= 80 ? 'bg-green-400' : pct >= 50 ? 'bg-yellow-500' : 'bg-red-500'
          const cBarColor = cpct >= 80 ? 'bg-blue-400' : cpct >= 50 ? 'bg-blue-300' : 'bg-blue-200'
          const typeLabel = DOC_TYPE_LABELS[r.doc_type] || r.doc_type
          const grouped = groupChecks(r.checks)
          const l1Checks = r.checks.filter(c => (c.level ?? 1) === 1)
          const l1Scoreable = l1Checks.filter(c => c.severity !== 'INFO')
          const l2Active = r.checks.filter(c => (c.level ?? 1) === 2 && !c.skipped)
          const l1Passed = l1Scoreable.filter(c => c.passed).length
          const l2Passed = l2Active.filter(c => c.passed).length

          return (
            <div key={i} className="border border-gray-200 rounded-lg overflow-hidden">
              <button
                onClick={() => setExpanded(isExp ? null : i)}
                className="w-full flex items-center justify-between px-4 py-3 hover:bg-gray-50 text-left"
              >
                <div className="flex items-center gap-3 flex-1 min-w-0">
                  <svg className={`w-4 h-4 text-gray-400 transition-transform shrink-0 ${isExp ? 'rotate-90' : ''}`}
                    fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                  </svg>
                  <span className="text-xs px-2 py-0.5 rounded bg-gray-100 text-gray-600 font-medium shrink-0">
                    {typeLabel}
                  </span>
                  <div className="min-w-0 flex-1">
                    <div className="text-sm font-medium text-gray-900 truncate flex items-center gap-2">
                      {r.label}
                      {r.scenario && SCENARIO_LABELS[r.scenario] && (
                        <span className={`text-[10px] px-1.5 py-0.5 rounded-full font-medium ${SCENARIO_LABELS[r.scenario].bg} ${SCENARIO_LABELS[r.scenario].color}`}>
                          {SCENARIO_LABELS[r.scenario].label}
                        </span>
                      )}
                    </div>
                    <div className="text-xs text-gray-500 truncate">
                      {l1Checks.length > 0
                        ? `${l1Passed}/${l1Scoreable.length} Pflichtangaben`
                          + (l2Active.length > 0 ? `, ${l2Passed}/${l2Active.length} Detailpruefungen` : '')
                        : r.url}
                    </div>
                  </div>
                </div>
                <div className="flex items-center gap-3 shrink-0 ml-3">
                  {r.error && r.error.startsWith("Auf der Website nicht gefunden") ? (
                    <span className="text-xs text-amber-700 font-medium px-2 py-0.5 bg-amber-100 rounded-full whitespace-nowrap">
                      Nicht gefunden
                    </span>
                  ) : r.error && r.error.startsWith("Nicht eingereicht") ? (
                    <span className="text-xs text-gray-500 font-medium px-2 py-0.5 bg-gray-100 rounded-full whitespace-nowrap">
                      Nicht eingereicht
                    </span>
                  ) : r.error ? (
                    <span className="text-xs text-red-600 font-medium">Fehler</span>
                  ) : (
                    <div className="flex flex-col gap-1">
                      <div className="flex items-center gap-2" title={`Pflichtangaben: ${l1Passed}/${l1Scoreable.length}`}>
                        <span className="text-[10px] text-gray-400 w-7">Pflicht</span>
                        <div className="w-14 h-1.5 bg-gray-200 rounded-full overflow-hidden">
                          <div className={`h-full rounded-full ${barColor}`} style={{ width: `${pct}%` }} />
                        </div>
                        <span className={`text-xs font-medium w-10 text-right ${
                          pct === 100 ? 'text-green-700' : pct >= 50 ? 'text-yellow-700' : 'text-red-700'
                        }`}>{pct}%</span>
                      </div>
                      {l2Active.length > 0 && (
                        <div className="flex items-center gap-2" title={`Detailpruefung: ${l2Passed}/${l2Active.length}`}>
                          <span className="text-[10px] text-gray-400 w-7">Detail</span>
                          <div className="w-14 h-1.5 bg-gray-200 rounded-full overflow-hidden">
                            <div className={`h-full rounded-full ${cBarColor}`} style={{ width: `${cpct}%` }} />
                          </div>
                          <span className="text-xs font-medium w-10 text-right text-blue-600">{cpct}%</span>
                        </div>
                      )}
                    </div>
                  )}
                </div>
              </button>

              {isExp && (
                <div className="px-4 py-3 border-t border-gray-100 bg-gray-50/50">
                  {r.error ? (
                    <p className="text-sm text-red-600">{r.error}</p>
                  ) : (
                    <div className="space-y-1">
                      {grouped.map((g) => {
                        const l1Info = g.check.severity === 'INFO' && !g.check.passed
                        return (
                        <div key={g.check.id}>
                          {/* L1 check */}
                          <div className="flex items-start gap-2">
                            <CheckIcon passed={g.check.passed} isInfo={l1Info} />
                            <div className="flex-1">
                              <div className={`text-sm ${
                                g.check.passed ? 'text-gray-700'
                                  : l1Info ? 'text-gray-500' : 'text-red-700 font-medium'
                              }`}>
                                {g.check.label}
                                {g.children.length > 0 && <L2Summary>{g.children}</L2Summary>}
                              </div>
                              {g.check.passed && g.check.matched_text && g.children.length === 0 && (
                                <div className="text-xs text-gray-400 mt-0.5 font-mono truncate">
                                  &quot;...{g.check.matched_text}...&quot;
                                </div>
                              )}
                              {!g.check.passed && g.check.hint && (
                                <div className={`text-xs mt-0.5 ${l1Info ? 'text-gray-400' : 'text-red-600/80'}`}>
                                  {g.check.hint}
                                </div>
                              )}
                            </div>
                          </div>

                          {/* L2 children — always visible */}
                          {g.children.length > 0 && (
                            <div className="ml-6 mt-0.5 mb-1 space-y-0.5 border-l-2 border-gray-200 pl-3">
                              {g.children.map((ch) => {
                                const chInfo = ch.severity === 'INFO' && !ch.passed && !ch.skipped
                                return (
                                <div key={ch.id} className="flex items-start gap-2">
                                  <CheckIcon passed={ch.passed} skipped={ch.skipped} isInfo={chInfo} />
                                  <div className="flex-1">
                                    <div className={`text-xs ${
                                      ch.skipped ? 'text-gray-400 italic'
                                        : ch.passed ? 'text-gray-600'
                                        : chInfo ? 'text-gray-400' : 'text-red-600 font-medium'
                                    }`}>
                                      {ch.label}
                                      {ch.skipped && ' (uebersprungen)'}
                                    </div>
                                    {ch.passed && ch.matched_text && (
                                      <div className="text-xs text-gray-400 mt-0.5 font-mono truncate">
                                        &quot;...{ch.matched_text}...&quot;
                                      </div>
                                    )}
                                    {!ch.passed && !ch.skipped && ch.hint && (
                                      <div className={`text-xs mt-0.5 ${chInfo ? 'text-gray-400' : 'text-red-500/80'}`}>
                                        {ch.hint}
                                      </div>
                                    )}
                                  </div>
                                </div>
                                )
                              })}
                            </div>
                          )}
                        </div>
                        )
                      })}
                      {r.word_count > 0 && (
                        <div className="text-xs text-gray-400 mt-2 pt-2 border-t border-gray-200">
                          {r.word_count} Woerter analysiert
                        </div>
                      )}
                    </div>
                  )}
                </div>
              )}
            </div>
          )
        })}
      </div>
    </div>
  )
}
