'use client'

import React, { useState } from 'react'
import { TextReference } from './TextReference'

interface ServiceInfo {
  name: string
  category: string
  provider: string
  country: string
  eu_adequate: boolean
  requires_consent: boolean
  legal_ref: string
  in_dse: boolean
  status: string
}

interface TextRef {
  found: boolean
  source_url: string
  document_type: string
  section_heading: string
  section_number: string
  parent_section: string
  paragraph_index: number
  original_text: string
  issue: string
  correction_type: string
  correction_text: string
  insert_after: string
}

interface ScanFinding {
  code: string
  severity: string
  text: string
  correction: string
  text_reference: TextRef | null
}

interface ScanData {
  pages_scanned: number
  pages_list: string[]
  services: ServiceInfo[]
  findings: ScanFinding[]
  discovered_documents?: DiscoveredDocument[]
  ai_detected: boolean
  chatbot_detected: boolean
  chatbot_provider: string
  missing_pages: Record<string, number>
  email_status: string
}

const STATUS_ICON: Record<string, { icon: string; color: string }> = {
  ok: { icon: '\u2713', color: 'text-green-600' },
  undocumented: { icon: '\u2717', color: 'text-red-600' },
  outdated: { icon: '~', color: 'text-yellow-600' },
}

const SEV_STYLE: Record<string, { bg: string; text: string; dot: string }> = {
  HIGH: { bg: 'bg-red-50 border-red-200', text: 'text-red-800', dot: 'bg-red-500' },
  MEDIUM: { bg: 'bg-yellow-50 border-yellow-200', text: 'text-yellow-800', dot: 'bg-yellow-500' },
  LOW: { bg: 'bg-blue-50 border-blue-200', text: 'text-blue-800', dot: 'bg-blue-500' },
  CRITICAL: { bg: 'bg-red-100 border-red-300', text: 'text-red-900', dot: 'bg-red-700' },
}

export function ScanResult({ data }: { data: ScanData }) {
  const [expandedCorrection, setExpandedCorrection] = useState<string | null>(null)
  const [expandedDoc, setExpandedDoc] = useState<string | null>(null)

  const undocCount = data.services.filter(s => s.status === 'undocumented').length
  const okCount = data.services.filter(s => s.status === 'ok').length
  const highCount = data.findings.filter(f => f.severity === 'HIGH' || f.severity === 'CRITICAL').length
  const docs = data.discovered_documents || []

  // Group findings by doc_title
  const docFindings: Record<string, ScanFinding[]> = {}
  const generalFindings: ScanFinding[] = []
  for (const f of data.findings) {
    if (f.doc_title) {
      if (!docFindings[f.doc_title]) docFindings[f.doc_title] = []
      docFindings[f.doc_title].push(f)
    } else {
      generalFindings.push(f)
    }
  }

  return (
    <div className="space-y-5">
      {/* Summary Bar */}
      <div className="grid grid-cols-4 gap-3">
        <div className="bg-gray-50 rounded-lg p-3 text-center">
          <p className="text-2xl font-bold text-gray-900">{data.pages_scanned}</p>
          <p className="text-xs text-gray-500">Seiten</p>
        </div>
        <div className="bg-green-50 rounded-lg p-3 text-center">
          <p className="text-2xl font-bold text-green-700">{okCount}</p>
          <p className="text-xs text-gray-500">Dokumentiert</p>
        </div>
        <div className="bg-red-50 rounded-lg p-3 text-center">
          <p className="text-2xl font-bold text-red-700">{undocCount}</p>
          <p className="text-xs text-gray-500">Nicht in DSE</p>
        </div>
        <div className="bg-purple-50 rounded-lg p-3 text-center">
          <p className="text-2xl font-bold text-purple-700">{docs.length}</p>
          <p className="text-xs text-gray-500">Dokumente</p>
        </div>
      </div>

      {/* Scanned Pages */}
      {data.pages_list?.length > 0 && (
        <details className="text-sm">
          <summary className="text-gray-600 cursor-pointer hover:text-gray-800">
            {data.pages_scanned} Seiten gescannt
          </summary>
          <ul className="mt-2 space-y-1 ml-4">
            {data.pages_list.map((p, i) => {
              const isMissing = data.missing_pages[p]
              return (
                <li key={i} className={`text-xs ${isMissing ? 'text-red-600' : 'text-gray-500'}`}>
                  {isMissing ? '\u2717' : '\u2713'} {p}
                </li>
              )
            })}
          </ul>
        </details>
      )}

      {/* Services Table */}
      {data.services.length > 0 && (
        <div>
          <h4 className="text-sm font-medium text-gray-700 mb-2">Dienstleister (SOLL/IST)</h4>
          <div className="border rounded-lg overflow-hidden">
            <table className="w-full text-sm">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">Status</th>
                  <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">Dienst</th>
                  <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">Land</th>
                  <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">In DSE</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100">
                {data.services.map((s, i) => {
                  const st = STATUS_ICON[s.status] || STATUS_ICON.ok
                  return (
                    <tr key={i} className={s.status === 'undocumented' ? 'bg-red-50' : ''}>
                      <td className={`px-3 py-2 font-bold ${st.color}`}>{st.icon}</td>
                      <td className="px-3 py-2">
                        <span className="font-medium text-gray-900">{s.name}</span>
                        <span className="text-gray-400 text-xs ml-2">{s.provider}</span>
                      </td>
                      <td className="px-3 py-2 text-gray-600">{s.country}</td>
                      <td className="px-3 py-2">{s.in_dse ? '\u2713' : <span className="text-red-600 font-medium">Nein</span>}</td>
                    </tr>
                  )
                })}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* === Document-Centric View === */}
      {docs.length > 0 && (
        <div>
          <h4 className="text-sm font-medium text-gray-700 mb-2">
            Rechtliche Dokumente ({docs.length})
          </h4>
          <div className="space-y-2">
            {docs.map((doc, i) => {
              const isExpanded = expandedDoc === doc.title
              const findings = docFindings[doc.title] || []
              const pct = doc.completeness_pct
              const barColor = pct >= 80 ? 'bg-green-500' : pct >= 50 ? 'bg-yellow-500' : 'bg-red-500'
              const statusLabel = pct >= 80 ? 'OK' : pct >= 50 ? 'Lueckenhaft' : 'Mangelhaft'
              const statusColor = pct >= 80 ? 'text-green-700 bg-green-50' : pct >= 50 ? 'text-yellow-700 bg-yellow-50' : 'text-red-700 bg-red-50'

              return (
                <div key={i} className="border border-gray-200 rounded-lg overflow-hidden">
                  <button
                    onClick={() => setExpandedDoc(isExpanded ? null : doc.title)}
                    className="w-full flex items-center justify-between px-4 py-3 bg-gray-50/50 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 ${isExpanded ? '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>
                      <div className="min-w-0 flex-1">
                        <div className="text-sm font-medium text-gray-900 truncate">{doc.title}</div>
                        <div className="text-xs text-gray-500">
                          {doc.word_count} Woerter
                          {findings.length > 0 && <span className="text-red-600 ml-2">{findings.length} Maengel</span>}
                        </div>
                      </div>
                    </div>
                    <div className="flex items-center gap-3 shrink-0 ml-3">
                      {/* Completeness bar */}
                      <div className="w-20 h-2 bg-gray-200 rounded-full overflow-hidden">
                        <div className={`h-full rounded-full ${barColor}`} style={{ width: `${pct}%` }} />
                      </div>
                      <span className={`text-xs font-medium px-2 py-0.5 rounded ${statusColor}`}>
                        {pct}%
                      </span>
                    </div>
                  </button>

                  {isExpanded && (
                    <div className="px-4 py-3 border-t border-gray-100 space-y-2">
                      {findings.length > 0 ? (
                        findings.map((f, fi) => {
                          const sev = SEV_STYLE[f.severity] || SEV_STYLE.MEDIUM
                          return (
                            <div key={fi} className="flex items-start gap-2 text-sm">
                              <span className={`w-2 h-2 rounded-full mt-1.5 shrink-0 ${sev.dot}`} />
                              <span className="text-gray-700">{f.text}</span>
                            </div>
                          )
                        })
                      ) : (
                        <p className="text-sm text-green-600">Alle Pflichtangaben vorhanden.</p>
                      )}
                      {doc.url && (
                        <a href={doc.url} target="_blank" rel="noopener noreferrer"
                          className="text-xs text-purple-600 hover:underline mt-2 inline-block">
                          Dokument oeffnen
                        </a>
                      )}
                    </div>
                  )}
                </div>
              )
            })}
          </div>
        </div>
      )}

      {/* General Findings (not associated with a specific document) */}
      {generalFindings.length > 0 && (
        <div>
          <h4 className="text-sm font-medium text-gray-700 mb-2">
            Allgemeine Findings ({generalFindings.length})
          </h4>
          <div className="space-y-2">
            {generalFindings.map((f, i) => {
              const sev = SEV_STYLE[f.severity] || SEV_STYLE.MEDIUM
              const corrKey = `gen-${i}`
              const isExp = expandedCorrection === corrKey
              return (
                <div key={i} className={`border rounded-lg p-3 ${sev.bg}`}>
                  <div className="flex items-start gap-2">
                    <span className={`text-xs font-bold px-2 py-0.5 rounded ${sev.text} bg-white`}>
                      {f.severity}
                    </span>
                    <p className="text-sm text-gray-800 flex-1">{f.text}</p>
                  </div>
                  {/* Text Reference (original text + position + correction) */}
                  {f.text_reference && (
                    <TextReference ref={f.text_reference} correction={f.correction} />
                  )}
                  {/* Fallback: correction without text reference */}
                  {!f.text_reference && f.correction && (
                    <div className="mt-2">
                      <button onClick={() => setExpandedCorrection(isExp ? null : corrKey)}
                        className="text-xs text-purple-600 hover:text-purple-800 font-medium">
                        {isExp ? 'Korrektur ausblenden' : 'Korrekturvorschlag'}
                      </button>
                      {isExp && (
                        <div className="mt-2 bg-white border border-gray-200 rounded-lg p-3 relative">
                          <pre className="text-xs text-gray-700 whitespace-pre-wrap font-sans">{f.correction}</pre>
                          <button onClick={() => navigator.clipboard.writeText(f.correction)}
                            className="absolute top-2 right-2 text-xs bg-gray-100 hover:bg-gray-200 px-2 py-1 rounded">
                            Kopieren
                          </button>
                        </div>
                      )}
                    </div>
                  )}
                </div>
              )
            })}
          </div>
        </div>
      )}
      {/* PDF Export Button */}
      <div className="pt-4 border-t flex gap-3">
        <button
          onClick={async () => {
            try {
              const res = await fetch('/api/sdk/v1/agent/scans/pdf', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ url: '', scan_type: 'scan', analysis_mode: 'post_launch', result: data }),
              })
              if (res.ok) {
                const blob = await res.blob()
                const url = URL.createObjectURL(blob)
                const a = document.createElement('a')
                a.href = url
                a.download = 'compliance-report.pdf'
                a.click()
                URL.revokeObjectURL(url)
              }
            } catch (e) { console.error('PDF export failed:', e) }
          }}
          className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-purple-700 bg-purple-50 border border-purple-200 rounded-lg hover:bg-purple-100 transition-colors"
        >
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
          </svg>
          PDF herunterladen
        </button>
      </div>
    </div>
  )
}
